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();
}

浙公网安备 33010602011771号