1. super理解为:父类的
2. super可以用来调用:属性、方法、构造器
3. super的使用
3.1我们可以在子类的方法或构造器中。通过使用"super.属性"或"super.方法"的方式,显式的调用父类中声明的属性或方法。但是,通常情况下,我们习惯省略"super."
3.2特殊情况:当子类和父类中定义了同名的属性时,我们要想在子类中调用父类中声明的属性,则必须显式的使用"super.属性"的方式,表明调用的是父类中声明的属性。
3.3特殊情况:当子类重写了父类中的方法以后,我们想在子类的方法中调用父类中被重写的方法时,则必须显式的使用"super.方法"的方式,表明调用的是父类中被重写的方法。
package com.binbin.test02;
public class Person {
int id = 1001;
String name;
int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println("人可以吃饭");
}
}
测试package com.binbin.test02;
public class Student extends Person {
int id = 2001;
char sex;
public Student() {
}
public Student(String name, int age, char sex) {
super(name, age); // 构造器使用super的方法
this.sex = sex;
}
public void showInfo() {
System.out.println("this id:" + this.id + ", name: " + name + ", sex:" + sex + ", age: " + age);
System.out.println("super id " + super.id);
this.eat(); // 当前类的eat方法
System.out.println();
super.eat(); // 父类的eat方法
}
@Override
public void eat() {
System.out.println("重写:人可以吃有营养的饭~~");
}
}
package com.binbin.test02;
public class SuperTest {
public static void main(String[] args) {
Student s = new Student();
s.showInfo();
Student s1 = new Student("Tom", 32, '男');
s1.showInfo();
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有