super 关键字的作用

super 关键字的作用
super 代表父类对象,在子类中访问父类成员
访问父类构造方法
在子类方法中调用且必须是第一句
正文
super 关键字与 this 关键字是不一样的,this 表示当前对象,而 super 关键字代表的是父类对象在程序中,它通常在子类中访问父类中的构造方法,当它在访问父类中的构造方法时,在子类构造方法中调用,但必须是第一条语句,super();调用无参数的构造方法,super(name);调用有参数的构造方法在调用有参数的构
造方法时特点:必须位于第一条语句。
访问父类属性:
super.name;
访问父类方法:
super.print();
父类中不能被继承的成员
private 修饰的私有成员
子类和父类不在同包,使用默认访问权限的成员
构造方法
访问修饰符

  • 以上为修饰符所访问的权限表。

super 关键字示例代码:

父类代码如下所示:

 class GZ {
   
       private String name;    private int age;    private String sex;     public GZ(){
   
            System.out.println("父类无参构造方法");     }     public GZ(String a,int b,String c){
   
            this.name=a;         this.age=b;         this.sex=c;         System.out.println("父类有参构造方法");     }
     //名字    public String getName(){
   
           return name;    }    public void setName(String name){
   
           this.name=name;        System.out.println("我叫"+name);    }    //年龄     public int getAge(){
   
           return age;     }     public void setAge(int age){
   
           this.age=age;        System.out.println("今年"+age);     }     //性别    public String getSex(){
   
           return sex;    }    public void setSex(String sex){
   
           this.sex=sex;        System.out.println("性别是"+sex);    }}
子类代码如下所示:
public class Demo extends GZ {
   
           public static void main(String[] args){
   
               GZ  input=new GZ();            input.setName("铁锤");            input.setAge(21);            input.setSex("男");        }    public Demo(){
   
               super();        System.out.println("子类无参构造方法");    }    public Demo(String a,int b,String c,String sex){
   
               super(a, b, c);        System.out.println("子类有参构造方法");    }    private String sex;    }
以上代码仅供参考学习
  • 不要盲目的抄代码

猜你喜欢

转载自blog.csdn.net/m0_65909361/article/details/127483269