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

前端 未结 6 842
予麋鹿
予麋鹿 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:55

    Longer answer:

    So really the way you'd do this is define Lion thus:

    public class Lion extends Animal {
      public Lion() {
         noise = "ROAR!!";
      }
    }
    

    So now for Lion instances the noise member variable of Animal has been updated to ROAR!!

    Of course you'd (almost) never actually have a public mutable member on a class like that in the wild.

提交回复
热议问题