super关键字
1. super.成员变量
class Person{
public String name; //成员变量
public Person(String name) {
this.name = name;
}
}
class Student extends Person{
String name = "student";
public Student(String name) {
super(name);
}
public void help() {
//调用父类的成员属性
System.out.println(name); //student 直接使用,优先使用局部变量
System.out.println(super.name); // B 直接使用父类的成员变量
}
}
class s {
public static void main(String[] args) {
Student p = new Student("B");
p.help();
}
}
输出结果 student
B
2. super.成员方法
class Person{
public String name;
public Person(String name) {
this.name = name; //Test
}
public void help() {
System.out.println(this.name+"Person");
}
}
class Student extends Person{
String name = "student";
public Student(String name) {
super(name); //Test
}
public void help() {
//调用父类的成员方法
super.help();
System.out.println(this.name+"Student"); //Student this调用的式同类中的变量
}
}
public class s {
public static void main(String[] args) {
Student p = new Student("Test");
p.help();
}
}
输出结果 Test Person
student Student
3. super():调用父类中的构造方法
3.1.1 隐式调用父类无参数构造方法super()
如果父类是无参构造,那么子类的构造方法会默认隐式的在第一行先调用父类无参数构造方法,所以super()无需手动进行调用;
public class Father{
int id;
public Father(){
System.out.println("父类构造方法");
}
}
public class Son extends Father{
public Son(){
//super(); //系统会默认生成,可有可无
System.out.println("子类构造方法");
}
}
public class Test{
public static void main(String[] args){
Son s = new Son();
}
}
输出结果 父类构造方法
子类构造方法
3.1.2 显式调用父类有参数构造方法super(id)
如果父类是含参构造,那么此时因为父类中没有无参数构造方法,所以子类继承父类时会报错,这时就需要我们手动的调用父类的有参构造方法super(id);
public class Father{
int id;
public Father(int id){
System.out.println("父类构造方法");
}
}
public class Son extends Father{
public Son(int id){
super(id); //手动调用父类的有参构造方法
System.out.println("子类构造方法");
}
}
public class Test{
public static void main(String[] args){
Son s = new Son(1);
}
}
输出结果: 父类构造方法
子类构造方法
super的用途:
public class MyTest {
public static void main(String[] args) {
Cat c1 = new Cat(3,"小李");
System.out.println("名字:" + c1.getName());
System.out.println("年龄:" + c1.getAge());
}
}
//父类,Animal类
class Animal {
//私有属性:名字
private String name;
//setter and getter
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
//构造函数
public Animal() {
}
public Animal(String name) {
this.name = name;
}
}
//子类,Cat类
class Cat extends Animal{
//私有字段:年龄
private int age;
//setter and getter
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
//构造函数
public Cat() {
}
public Cat(int age) {
this.age = age;
}
public Cat(int age,String name) {
super(name); //访问了父类的name属性
this.age = age;
}
}
特别注意 当父类没有提供无参构造方法时 子类的构造器调用父类的有参构造器时,必须在构造器的首行 使用super();
注意:普通方法中不能调用构造器
super关键字的出现使子类和父类的分功明确