Java重寫構造方法


public class TestSuper {
    public static void main(String[] args) {
        new ChildClass("alex", 10, 198).f();
    }
}

class Parent {

    Parent() {
        System.out.println("father");
    }

    public void drive() {
        System.out.println("parent can driving");
    }
}

class Child extends Parent {
    Child() {
        System.out.println("son");
    }

    public void drive() {
        super.drive();
        System.out.println("child can driving");
    }
}


class FatherClass {
    public int value;
    public String username;
    public int age;

    //父類的構造方法
    FatherClass(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public void f() {
        value = 100;
        System.out.println("FatherClass.value=" + value);
    }
}

class ChildClass extends FatherClass {
    public int value;
    int height;

    /**
     * 如果重寫構造父類的構造方法,則子類的要給上面的內容給寫好,然后用super引入父類的屬性
     *
     * @param username
     * @param age
     * @param height
     */
    
    ChildClass(String username, int age, int height) {
        super(username, age);
        this.height = height;
        System.out.println("child construct");
        System.out.println(this.username);
    }

    public void f() {
        super.f();
        value = 200;
        System.out.println("ChildClass.value=" + value);
        System.out.println(value);
        System.out.println(super.value); //調用父類對象的成員變量
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM