super 、this的使用

权限控制表

修饰词本类同一个包的类继承类其他类
private × × ×
无(默认) × ×
protected ×
public

super和this在类的方法中进行使用,举例:

public class Demo01 {
   protected int num;

   public Demo01() {
       this.num = 1;
  }
   public void out(){
       System.out.println(num);
  }
}

public class Demo02 extends Demo01{
   private int num = 1;
   public Demo02()
  {
       this.num = 5;
  }
   public void test(){
       System.out.println(num);  
       System.out.println(this.num);
       System.out.println(super.num);
  }
}

主启动类

public class Application {
   public static void main(String[] args) {
       Demo02 zzz =new Demo02();
       zzz.test(2);
  }
}

输出结果为:2

5

1

调用父类的构造器

    public Demo02()
  {

       super();
       this.num = 5;
  }

在构造器中调用其他构造器

    public Demo02()
  {
       this(1);
  }
   public Demo02(int num)
  {
       this.num = num;
  }

调用父类的方法

    public void xxx(){
      super.test();
  }

 

posted @ 2020-12-22 15:50  飒飒阿萨德  阅读(98)  评论(0)    收藏  举报