代码改变世界

this super的用法

2018-05-21 16:40  yelena  阅读(171)  评论(0编辑  收藏  举报

this关键词:谁调用代表谁

在构造函数中的应用格式:this(参数)

package com.oracle.Demo05;

public class Animal {
    private String name;
    private int age;
    public Animal(){
        
    }
    public Animal(String name){
        this.name = name;
    }
    public Animal(String name,int age){
        this(name);
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void eat(){
        System.out.println(name+age+"在吃饭");
    }
    public void sleep(){
        System.out.println(name+age+"在睡觉");
    }

    
}

 

成员变量和局部变量同名时的使用:

判断是否是同龄人问题

public boolean compare(Person p){
        return this.age == p.age;
    }

this代表的是调用者

 

 

super关键字的使用

super和this 关键字都必须在第一行 所以两者不能同时出现

调用父类的构造函数

package com.oracle.Demo03;

public class Person {
     private String name;
     private int age;
     public Person(){
         
     }
     public Person(String name,int age){
         this.name = name;
         this.age = age;
     }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
     
}
package com.oracle.Demo03;

public class Student extends Person {
    public Student(){
        
    }
    public Student(String name,int age){
        super(name,age);
        
    }
}
package com.oracle.Demo03;

public class Worker extends Person {
    public Worker(){
        
    }
    public Worker(String name,int age){
        super(name,age);
    }
}

 

调用父类的成员变量和成员方法