您现在的位置是:首页 > 文章详情

Java 面向对象 之 super 关键字

日期:2018-08-21点击:489

http://www.verejava.com/?id=17159596599630

/**

    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("只有通过自己的勤奋劳动, 才能得到果实 是最大的宝藏");
    }
}

http://www.verejava.com/?id=17159596599630

原文链接:https://yq.aliyun.com/articles/626856
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章