理解
super 用法:
1. 访问父类构造函数,super()无参构造为默认,super(参数)有参构造,必须出现在子类构造方法的首行
2. 访问父类成员变量,super.父类变量名
3. 访问父类方法,super.父类方法名()
this 意义:当局部变量和成员变量发生冲突,用this区分
1. 调用构造方法,this(),this(参数)
2. 调用成员变量,this.对象属性名
3. 调用成员方法,this.对象方法名
区分
- super是当前对象的父对象的引用,本质上是一个Java关键字,也可以理解指向自己父类对象的一个指针
this指的是当前对象的引用,本质上是个对象本身的指针,在同一个类中调用其他方法
注意
- super和this不能同时出现在一个构造方法里
因为this必然调用其他构造方法,其他的构造方法中肯定有super存在,所以在同一个构造方法里有相同的语句,会失去语句的意义,编译器也不会通过 - super和this都不能在static环境中适用(static变量、方法、语句块)
因为它们都指的是对象
看影响的例子
package com.aaa.p060302;
class Animal{
protected String name;
protected int age;
public Animal(){
}
public Animal(String name,int age){
this.name = name;
this.age = age;
}
public void show(){
System.out.println("父类"+name+"年龄"+age);
}
}
class Dog extends Animal{
String color;
int age = 10;
String name = "哈哈";
public Dog(String xm,int xage,String xc){
super.name = xm;
super.age = xage;
color = xc;
}
@Override
public void show(){
System.out.println("子类age"+age);
super.show();
System.out.println("子类color"+color);
}
}
public class Demo0604 {
public static void main(String[] args) {
Dog d = new Dog("旺财",100,"黄色");
d.show();
}
}
看下debug时候,实例d的参数情况:
运行结果: