zoukankan      html  css  js  c++  java
  • 构造方法的继承

    class PersonA
    {
        String name; //姓名
        int age;     //年龄
        //有参数构造方法
        public PersonA(String name,int age)
        {
            this.name=name;
            this.age=age;
        }
        //无参数构造方法
        public PersonA ()
        {
            this.name="张三";
            this.age=20;
        }
        void print()
        {
        System.out.println("class PersonA : "+"Name:"+this.name+": age: "+this.age);
        }
        
        }
    //子类
    class StudentA extends PersonA
    {
        String  name;
        int classno;  //班号
        //无参构造函数
        public StudentA()
        {
            super("马云",54); //调用父类的成员方法
            this.name="马化腾";
            this.age=43;
        }
        public StudentA(String name,int age,int classno)
        {
          this.name=name;
          this.age=age;
          this.classno=classno;
          
        }
        void sprint()
        {
            System.out.println("class StuentA:"+"Name :"+this.name+"Age:"
        +this.age+"Classno:"+this.classno);
            System.out.println("父类的成员变量方法:"+super.name);
        }
        
        }
    public class Constructorlnherit {
        public static void main(String[]args)
        {
            StudentA obj1=new StudentA();
            StudentA obj2=new StudentA("李彦宏",46,3);
            obj1.print();
            obj1.sprint();
            //
            obj2.print();
            obj2.sprint();
            
            
        }
        

    }
    /*
     * super代表当前对象的直接父类对象
     * 访问父类的无参构造方法:super();
     * 访问父类的有参构造方法:super(参数列表);
     * 访问父类的成员变量方法:super.成员变量方法;
     */
    1.子类无条件继承父类的无参数的构造方法。

    2.子类没有定义构造方法时,则它将继承父类的无参数构造方法作为自己的构造方法:如果子类定义了构造方法,则在创建对象事,将先执行来自继承的父类的无参数构造发方法

    然后执行自己的构造方法。

    3.对于父类的构造方法,子类可以通过自己的构造方法中使用super关键字来调用它,但这个调用语句必须是子类构造方法中的第一条可执行语句

    编程是一门艺术,要爱就要深爱。
  • 相关阅读:
    netty 学习总结
    tps 真正理解
    Eureka 学习
    h5前端编译项目问题
    web自动化学习
    python unittest自动化执行的几种方式
    python pip install XX 出现Could not fetch URL https://pypi.python.org/simple/pool/: There was a problem confirming
    TypeError: 'module' object is not callable
    简明HTML+CSS实现圣杯布局方法及要点(浮动实现)
    负Margin技术,轻松实现 1.自适应两列布局,2.元素垂直居中(相对定位)
  • 原文地址:https://www.cnblogs.com/pwhit/p/4918939.html
Copyright © 2011-2022 走看看