java通过super调用父类的属性和方法:

2019年2月15日23:30:17 发表评论 1,023 views
import java.util.SplittableRandom;

/**
 * Created by xabcd on 2019/2/15.
 */
public class Person7
{
    String name;
    int age;
    public Person7()
    {}
    public String talk(){
        return "我是:"+this.name+",今年:"+this.age+"岁";
    }
//    public Person7(String name,int age){
//        this.name=name;
//        this.age= age;
        //System.out.println("1.public Person7(){}" );

    }

class Studenttt extends Person7 {
    String school;

    public Studenttt(String name, int age, String school) {
        super.name = name;
        super.age = age;
        System.out.print(super.talk());
        this.school = school;

        //在这里调用父类的构造方法
//        super("张三",25);
        //System.out.println("2.public Student(){}");
    }

}





public class testjicheng2 {
    public static void main(String[] args) {
        Studenttt s = new Studenttt("张三", 25, "北京");
//        s.school= "北京";
        System.out.println(",学校:" + s.school);
//        System.out.println("姓名:"+s.name+",年龄"+s.age+",学校:"+s.school);

    }
}



结果:
我是:张三,今年:25岁,学校:北京




方法。 但是 细心 的 读者 在 本例 中 可以 发现, 如果 第 21、 22、 25 行 换成 this 调用 也是 可以 的, 那 为什么 还要 用 super 呢? 读者 看完 下面 的 内容 就可以 知道 什么时候 应该 这样 使用。

 

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: