码迷,mamicode.com
首页 > 编程语言 > 详细

Constant issues in Java inheritance

时间:2015-08-17 23:36:18      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!