2016-01-22 57 views
2

我基本上是在尋找一種方式來修改與修飾,並在方法體的一些額外的行下面的源代碼,所以它打印出在我的控制檯如下:如何控制與修飾符的繼承?

1g 
1hb 
2f 
1g 
2hb 
1hb 

它的一個鍛鍊我的大學課程而我似乎無法將我的頭圍繞在它周圍。 Iam只允許更改方法體,以免除println行以及更改方法的修飾符。我應該如何做到這一點,以及修飾語在這裏與繼承有何關係?我如何重載方法以獲得所需的結果?

這是我的主要方法:

public class Poly { 
    public static void main(String args[]) { 
     Poly1 a = new Poly1(); 
     a.g(); 

     Poly2 b = new Poly2(); 
     b.f();  
    } 
} 

,這是我的第一類:

public class Poly1 { 

public void f() { 
    System.out.println("1f"); 
    g(); 
} 

private void g() { 
    System.out.println("1g"); 
    h(10); 
} 

protected void h(int i) { 
    System.out.println("1hi"); 
} 

void h(byte b) { 
    System.out.println("1hb"); 
} 
} 

和下面是我的第二類:

public class Poly2 extends Poly1 { 

protected void f() { 
    System.out.println("2f"); 
    Poly1 c=new Poly1(); 
    g(); 
    h(); 
} 

public void g() { 
    System.out.println("2g"); 
    h(18); 
} 

public void h(int i) { 
    System.out.println("2hi"); 
} 

public void h(byte b) { 
    System.out.println("2hb"); 
} 
} 

回答

0
public class Poly1 { 
    public void f() { 
     System.out.println("1f"); 
     g(); 
    } 

    public void g() { 
     System.out.println("1g"); 
     h((byte) 10); // cast to byte to invoke the overloaded method void 
         // h(byte b) 
    } 

    protected void h(int i) { 
     System.out.println("1hi"); 
    } 

    void h(byte b) { 
     System.out.println("1hb"); 
    } 
} 


public class Poly2 extends Poly1 { 

    public void f() { //change from protected to public since the visibility of an overidden method Cannot be reduced 
     System.out.println("2f"); 
     Poly1 c = new Poly1(); 
     c.g(); // invoke the methode g of Poly1 
     h((byte) 10); 
    } 

    public void g() { 
     System.out.println("2g"); 
     h(18); 
    } 

    protected void h(int i) { 
     System.out.println("2hi"); 
} 

    public void h(byte b) { 
     System.out.println("2hb"); 
    } 
} 
+0

是,這基本上也是我的解決方案。我只是不能讓第5行中的2hb工作。它以某種方式必須進入之間,但我不知道如何? – ph1rone

+0

super.g(); super.h((byte)10); – hasnae

+0

非常感謝!我終於明白超級...乾杯! – ph1rone