标签:
This is the super class Human:
class Human { String name = "Human"; String sex = "Humanity"; public String getHuman(){ return this.name+";"+this.sex+";"; } }
These two are his subclasses:
class Man extends Human{ String name = "Adam"; String sex = "Male"; Man(String name){ this.name = name; System.out.println(this.name+";"+this.sex+";"); } }
class Woman extends Human{ String name = "Eva"; String sex = "Female"; Woman(String name){ this.name = name; System.out.println(this.name+";"+this.sex+";"); } }
And this is the test main function:
public class ObjectTest { public static void main(String[] args) { Human human = new Human(); Woman Kate = new Woman("Kate"); Man Jim = new Man("Jim"); System.out.println(Kate.getHuman()+Jim.getHuman()+human.getHuman()); } }
The final result is:
Kate;Female;
Jim;Male;
Human;Humanity;Human;Humanity;Human;Humanity;
So, here is the problem. As we know, the override in Java makes us can rewrite the method of super class in its subclass. However, we can‘t override the content in the super class. When the content in subclass has the same name, the origin content in super class would been hidden in the subclass. By the time there are actually two contents who have the same name in the subclass! When we use the method in super class, the method would still invoking the super class‘ origin content.
So, the conclusion is that we should try to avoid operating content in the process of inherit. Use setter and getter method instead to manipulate the content is much more safer and reasonable.
Constant issues in Java inheritance
标签:
原文地址:http://www.cnblogs.com/suncosmo/p/4737980.html