转载

java入门第二季--继承--java中的继承初始化顺序

java中的继承初始化顺序

java入门第二季--继承--java中的继承初始化顺序

java入门第二季--继承--java中的继承初始化顺序

父类和子类

/javaDemo3/src/com/imooc/Animal.java

package com.imooc;

public class Animal {
    public int age;
    public String name;
    public void eat() {
        System.out.println("年龄:"+age+ "动物可以吃东西" );
    }
    public Animal() {
        System.out.println("Animal类执行了" );
    }
}

/javaDemo3/src/com/imooc/Dog.java

package com.imooc;

public class Dog extends Animal {
    public void eat() {
        System.out.println("年龄:"+age+ "狗可以吃东西" );
    }
    public Dog() {
        System.out.println("Dog类执行了" );
    }
}

/javaDemo3/src/com/imooc/Initail.java

package com.imooc;

public class Initail {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Dog dog = new Dog();
        dog.age = 10;
        dog.name = "aa";
        dog.eat();
    }

}

java入门第二季--继承--java中的继承初始化顺序

对象的属性和构造方法

/javaDemo3/src/com/imooc/Animal.java

package com.imooc;

public class Animal {
    public int age = 10;
    public String name;
    public void eat() {
        System.out.println("年龄:"+age+ "动物可以吃东西" );
    }
    public Animal() {
        age = 20;
        System.out.println("Animal类执行了" );
    }
}

/javaDemo3/src/com/imooc/Initail.java

package com.imooc;

public class Initail {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Animal animal = new Animal(); 
        System.out.println("animal的age:" + animal.age );
        Dog dog = new Dog();
        dog.age = 10;
        dog.name = "aa";
        dog.eat();
    }

}

java入门第二季--继承--java中的继承初始化顺序

原文  https://segmentfault.com/a/1190000017980675
正文到此结束
Loading...