2017-06-29 18 views
0

我創建了2個班級,我想在B級方法中使用A級
創建了A級級別 我使用保護因爲我創建了一個超在我的代碼,不介意它我創建了2個班級,我想要使用B級方法中的A級

public class A { 
protected String modulname; 
     protected String verantwortliche; 
     protected int sws; 
     protected int credits; 

     public A (String modulname, String verantwortliche, int sws, int credits){//beginning of the methode of class A 
      this.modulname =modulname; 
      this.verantwortliche = verantwortliche; 
      this.sws= sws; 
      this.credits = credits; 
     } 
     public class B { 
     private String pruefer; 
     private double leistungeninprozent; 
     //i want to use the Attributes/Constructors form class A in the class B 
     //an put it like this: 
     public B (class A, String pruefer, double 
      leistungeninprozent){ 
       this.leistungeninprozent = leistungeninprozent; 
       this.modul = modul; 
       this.pruefer = pruefer; 
     } 

回答

2

改變這一點:

public B (class A, String pruefer, double 
     leistungeninprozent){ 
      this.leistungeninprozent = leistungeninprozent; 
      this.modul = modul; 
      this.pruefer = pruefer; 
    } 

這樣:

public B (A aObject, String pruefer, double //change "class A" to "A aObject" 
     leistungeninprozent){ 
      this.leistungeninprozent = leistungeninprozent; 
      this.modul = modul; 
      this.pruefer = pruefer; 
    } 

然後你可以像這樣在B的構造函數中訪問它:aObject.modulname

0

它很好用。我如何實現toString方法? 我的意思是將類A的toString實現到類b的toString中。

那了toString形式A類:

@Override 
    public String toString() { 
     return "Module [Modulname=" + modulname + ", Verantwortliche=" + verantwortliche + ", SWS=" + sws 
       + ", Credits=" + credits + "]"; 
    } 

也就是說從B級了toString梅索德:

@Override 
    public String toString() { 
     return "Leistungen [Pruefer=" + pruefer + ", LeistungeninProzent=" + leistungeninprozent 
       + "]"; 
    } 

現在我想從兩個不同的類做只有一個的toString梅索德。

0

在學習Java的這個非常早期的階段,我會建議避免使用嵌套類。 B的實例只能存在於A類的實例中。

要回答您的問題,參數應表示類的實例,而不是類本身。然後在方法內成爲局部變量,並通過它可以訪問它的字段和方法。