java入門第二季--繼承--java中的方法重寫

java中的方法重寫

clipboard.png

重寫前

clipboard.png

/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+ "動物能夠吃東西" );
    }
    
}
/javaDemo3/src/com/imooc/Dog.java
package com.imooc;

public class Dog extends Animal {

}
/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();
    }

}

clipboard.png

重寫後

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

public class Dog extends Animal {
    public void eat() {
        System.out.println("年齡:"+age+ "狗能夠吃東西" );
    }
}

clipboard.png

相關文章
相關標籤/搜索