这篇文章将为大家详细讲解有关Java面向对象之super关键字怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
/**
this: 代表当前类的引用
1. 当局部变量和成员变量同名时, 成员变量要加 this 限定
2. 实例化时 可以用 this 调用当前类的构造方法, 必须写在第一行
3. 可以用 this 调用当前类的 普通方法
super : 代表当前父类的引用
1. 实例化子类时, 可以用 super 调用父类的 非私有方法
2. 实例化子类时. 可以用 super 调用父类的 构造方法 , 必须写在第一行
3. 在子类的方法中 , 可以用 supe 调用父类的 非私有方法.
*/public class Test1 { public static void main(String[] args) { // 实例化 农夫
Father father = new Father();
father.setName("农夫");
father.setAge(90);
System.out.println(father.getAge() + " 岁 " + father.getName() + " 有 " + father.getWealth());
Father father = new Father("农夫", 90);
System.out.println(father.getAge() + " 岁 " + father.getName() + " 有 " + father.getWealth());
Son son = new Son("农夫", 90);
System.out.println("儿子知道父亲的 : " + son.getAge() + " 岁 " + son.getName() + " 有 " + son.getWealth());
son.work();
}
}//父类class Father {
private String name; private int age; private String wealth; public Father() {
wealth = "100两黄金";
} public Father(String name, int age) { this(); this.name = name; //this.age=age;
this.setAge(90);
} public void work() {
System.out.println("耕地");
} public String getWealth() { return wealth;
} public void setAge(int age) { this.age = age;
} public int getAge() { return age;
} public void setName(String name) { this.name = name;
} public String getName() { return name;
}
}//子类class Son extends Father { public Son(String name, int age) { super(name, age); //super.setName(name);
//super.setAge(age);
} public void work() { super.work();
System.out.println("儿子 寻找黄金宝藏");
System.out.println("只有通过自己的勤奋劳动, 才能得到果实 是最大的宝藏");
}
}
关于“Java面向对象之super关键字怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/10054744/viewspace-2213145/