码迷,mamicode.com
首页 > 编程语言 > 详细

谈谈java中的super和this关键字

时间:2019-04-10 13:14:36      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:sys   win   wal   png   构造函数   技术   mamicode   test   调用   

知识点:

             在java类中使用super引用父类的成分,用this引用当前对象

              this可以修饰属性、构造器、方法

              super可以修饰属性、构造器、方法

 

一:this关键字

  this可以修饰属性、构造器、方法;用this引用当前对象

  (1)this修饰属性,调用类的属性

//set方法
public void setName(String name) {
this.name = name;
}

//有参数构造函数
public Person(String name){
this.name=name;
}

(2)this修饰构造器,在构造器中通过 this(形参)的方式显示地调用本类中,其他重载的指定的构造器(在构造器内部必须声明在首行
public Person(){
System.out.println("调用当前类的无参构造函数");
}
public Person(String name){
this();//调用本类中无参构造函数
this.name=name;
}

public Person(String name,int age){
this(name); //在构造器中通过 this(形参)的方式显示地调用本类中,其他重载的指定的构造器(在构造器内部必须声明在首行)
this.age=age;
}
(3)this修饰成员方法,调用类的方法
public void showInfo(){
System.out.println("调用当前类的成员方法showInfo");
}
public void showAllInfo(){
this.showInfo();
System.out.println("调用当前类的成员方法showAllInfo");
}

二:super关键字

super可以修饰属性、构造器、方法;用super引用父类的成分

(1)super修饰属性,引用父类的属性
//动物
public class Animal{
public String gender="男";//性别

public Animal(){
this.name="张三";
System.out.println("动物无参构造函数!");
}
}
//人
public class Person extends Animal {
public Person(){
super.gender="女";//子类无参构造函数中,调用父类的属性,并修改父类的gender属性
System.out.println("人无参构造函数!");
}
}
(1)super修饰构造方法,引用父类的构造方法
//生物
public class Creature {
public Creature(){
System.out.println("生物无参构造函数!");
}

}
//动物
public class Animal extends Creature{
public Animal(){
super();
System.out.println("动物无参构造函数!");
}

}
//人
public class Person extends Animal {
public Person(){
super();
System.out.println("人无参构造函数!");
}
}
//测试类
public class Test {
public static void main(String[] args) {
Person p=new Person();//初始化p实例
}
}
 

运行结果:
技术图片
 

谈谈java中的super和this关键字

标签:sys   win   wal   png   构造函数   技术   mamicode   test   调用   

原文地址:https://www.cnblogs.com/shuaifing/p/10682628.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!