2016-01-22 59 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