What is object field initialization and constructor order in Java

前端 未结 3 2013
半阙折子戏
半阙折子戏 2020-12-06 18:33

I ended up the following scenario in code earlier today (which I admit is kinda weird and I have since refactored). When I ran my unit test I found that a field initializat

3条回答
  •  失恋的感觉
    2020-12-06 19:28

    Here's an example of polymorphism in pseudo-C#/Java:

    class Animal
    {
       abstract string MakeNoise ();
    }
    
    class Cat : Animal {
        string MakeNoise () {
        return "Meow";
        } 
    }
    
    class Dog : Animal {
        string MakeNoise () {
        return "Bark";
        }
    }
    
    Main () {
        Animal animal = Zoo.GetAnimal ();
        Console.WriteLine (animal.MakeNoise ());
    }
    

    The Main function doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.

    class A
    {
    A(int number)
       {
        System.out.println("A's" + " "+ number);
       }
    }
    
    class B
    {
    A aObject = new A(1);
    B(int number)
        {
        System.out.println("B's" + " "+ number);        
        }
    A aObject2 = new A(2);
    }
    
    public class myFirstProject {   
    public static void main(String[] args) {
        B bObj = new B(5);
       }
    }
    

    out: A's 1 A's 2 B's 5

    My rules: 1. Don't initialize with the default values in declaration (null, false, 0, 0.0...). 2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field. 3. If the value of the field changes because of a constructor parameter put the initialization in the constructors. 4. Be consistent in your practice. (the most important rule)

    public class Dice
    {
    private int topFace = 1;
    private Random myRand = new Random();
    
    public void Roll()
       {
       // ......
       }
    }
    

    or

    public class Dice
    {
    private int topFace;
    private Random myRand;
    
    public Dice()
        {
        topFace = 1;
        myRand = new Random();
        }
    
    public void Roll()
       {
        // .....
       }
    }
    

提交回复
热议问题