super
是一个关键字,字母全部小写this
关键字
this
能出现在实例方法和构造方法中
this
的语法是"this.
"、"this()
"。
this
不能使用在静态方法中。
this.
在大部分情况下可以省略,但是在区分局部变量和实例变量的时候不能省略。
public void setName(String name){
this.name = name;
}
this()
只能出现在构造方法第一行,通过当前的构造方法去调用“本类”中其他的构造方法,目的是:代码复用。
super
关键字
super
能出现在实例方法和构造方法中。super
的语法是:"super.
"、"super()
"。super
不能使用在静态方法中。super.
大部分情况下是可以省略,但如果在父和子中有同名的属性,或者说有相同的方法,想在子类中访问父类的数据,这时super.
是不可以省略的。super()
只能出现在构造方法第一行,通过当前的构造方法去调用“父类”中的构造方法,目的是:创建子类对象的时候,先初始化夫父类型的特征.super()
表示通过子类的构造方法调用父类的构造方法。模拟现实世界中的这种场景:要想有儿子,需要现有父亲。super(实参)
的用法public class SuperTest {
public static void main(String[] args) {
Student s = new Student("xiaoming",18,13);
System.out.println(s.getName()+","+s.getAge()+","+s.getNo());//xiaoming,18,13
}
}
class People{
private String name;
private int age;
int no;
public People() {
}
public People(String name, int age) {
this.name = name;
this.age = age;
}
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 int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
}
class Student extends People {
public Student() {
}
public Student(String name, int age, int no) {
super(name, age);//通过子类的构造方法调用父类的构造方法
this.no = no;
}
}
super
调用父类方法public class SuperTest03 {
public static void main(String[] args) {
Cat c = new Cat();
c.yiDong();
/*
运行结果:
Cat move!
Cat move!
Animal move!
*/
}
}
class Animal{
public void move(){
System.out.println("Animal move!");
}
}
class Cat extends Animal{
public void move(){//对父类中move()方法进行重写
System.out.println("Cat move!");
}
public void yiDong(){//单独编写一个子类特有的方法
this.move();
move();
super.move();//super. 不仅可以访问属性,也可以访问方法
}
}
/*
在父和子中有同名的属性,或者说有相同的方法,
如果此时想在子类中访问父类中数据,必须使用“super.”进行区分!
*/
super
使用方法总结super.属性名
:访问父类的属性。super.方法名(实参)
:访问父类的方法。super(实参)
:调用父类的构造方法。this()
又没有super()
的话,默认会有一个super()
。表示通过当前的无参构造方法去调用父类的无参构造方法。所以必须保证父类的无参构造方法是存在的。this()
和super
不能共存,它们都是只能出现在构造方法第一行。new
什么对象,最后老祖宗的Object
类的无参构造方法一定会执行。(Object
类中的无参构造方法是处于“栈顶”的)栈顶的特点:最后调用,但是最先执行结束。(后进先出原则)super.
加以区分。this.name
:当前对象的name
属性。super.name
:当前对象的父类型特征中的name
属性。super
和this
不能使用在静态方法中public class SuperTest02 {
public void doSome(){//实例方法
System.out.println(this);
//输出引用的时候,会自动调用引用的toString()方法
// System.out.println(this.toString());
// System.out.println(super);//编译报错
}
// this和super不能使用在static静态方法中
public static void doOther(){
// System.out.println(this);
// System.out.println(super);
}
public static void main(String[] args) {
SuperTest02 st = new SuperTest02();
st.doSome();
// main方法时静态的
// 错误的
// System.out.println(this);
// System.out.println(super);
}
}
/*
通过这个测试得出结论
super不是引用。super也不保存内存地址,super也不指向任何对象。
super只是代表当前对象内部的那一块父类型的特征
*/
原文:https://www.cnblogs.com/yxc-160206/p/13215233.html