this和super

来源:互联网 发布:eclipse java项目结构 编辑:程序博客网 时间:2024/06/01 21:10

1.this
当一个对象创建好以后,java虚拟机就会给他分配一个引用自身的指针:this。所有对象默认的引用名均为this。

用法1:在一个实例方法内部,局部变量或参数和实例变量同名,实例变量被屏蔽,因此采用this.来访问。

public class Test6 {      String name="Mick";      public void print(String name){          System.out.println("类中的属性 name:"+this.name);    //输出  类中的属性 name:Mick        System.out.println("局部传参的属性:"+name);    //输出局部传参的属性:Orson    }         public static void main(String[] args) {          Test6 tt=new Test6();          tt.print("Orson");      }  }  

用法2:在类的构造方法中,通过this语句来调用这个类的另一个构造方法。(重载构造方法)

public class Employee {      private String name;    private int age;    public static void main(String[] args) {        Employee employee1=new Employee("张三", 25);        Employee employee2=new Employee(";里斯");        Employee employee3=new Employee();    }    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 Employee(String name,int age){        this.age=age;        this.name=name;    }    /**当雇员的姓名已知,年龄未知时,调用此构造方法*/    public Employee(String name){        this(name, -1);      //调用了Employee(String name,int age)构造方法    }    /**当雇员的年龄,姓名都未知时,调用此构造方法*/    public Employee(){        this("无名氏");         //调用了 Employee(String name)构造方法    }}  

用法3.在一个实例方法内访问当前实例的引用。

this只能在构造方法或实例方法中使用this关键字,而在静态方法和静态代码块不能使用this关键字。

2.super
(1)在类的构造方法中,通过super语句调用这个类的父类的构造方法。
(2)在子类中访问父类被屏蔽的方法和属性。

public class Sub extends Base {    String var="Sub Varible";   //隐藏父类的var变量    void method(){        System.out.println("Sub method");     //覆盖父类的method方法    }    void test(){        String var="Local Varible";        System.out.println("var is "+var);   //打印test()方法的局部变量        System.out.println("this.var is "+this.var);   //打印Sub实例中的实例变量        System.out.println("super.var is "+super.var);      //打印Base类中的定义的实例变量        method();   //调用Sub实例的method()方法        this.method();    //调用Sub实例的method()方法        super.method();   //调用Base的method()方法    }    public static void main(String[] args) {        Sub sub=new Sub();        sub.test();    }    //输出    //var is Local Varible    //this.var is Sub Varible    //super.var is Base Varible    //Sub method    //Sub method    //Base method}

super只能在构造方法或实例方法中使用this关键字,而在静态方法和静态代码块不能使用this关键字。

原创粉丝点击