How does instance variable invocation work when you do A thing = new B(); where B is a subclass of A?

前端 未结 6 800
予麋鹿
予麋鹿 2021-01-27 17:54

This is probably answered somewhere, but I have no idea what to search for. Imagine you have the following...

The superclass, Animal.java

public class An         


        
6条回答
  •  情深已故
    2021-01-27 18:42

    You can not override fields, new declaration of noise in Lion hides parent's noise attribute. do like this:

    public class Lion extends Animal {
    
    //    public String noise = "ROAR!!";  // <---- Remove this line
    
        public Lion() {
            noise = "ROAR";
        }
    
        public String toString() {
            return noise;
        }
    }
    

提交回复
热议问题