2013-06-20 57 views
-6

嗨,大家好我創建一個程序是一個購物車,我試圖創建一個toString()方法。私人變量與toString()

這是我GolfHat類

package ShoppingCart; 

public class GolfHat extends Product { 

    private String name; 
    private String colour; 
    private String make; 
    private double price; 

    public GolfHat(String type, String make, String name, String colour,double price) { 

     this.type = "hat"; 
     name = name; 
     colour = colour; 
     make = make; 
     price = price; 

    } 

和我的產品類是這個

package ShoppingCart; 

public class Product { 

    public String type ; 

    public String toString(){ 
     if (type=="hat") { 

      System.out.println ("Type: " + type + "\t" + "Make: " + make); 
      return type; 
     } 

     if (type=="Glove"){ 

     } 
      return "cant find"; 

    } 

它不會讓我用make變量,我認爲它不會讓我做這件事引起我的變量私人然而,對於我的部分評估,我需要展示一個封建和im鬥爭的例子,看看我能夠做到的其他事情

+1

開始[這裏](http://en.wikipedia.org/wiki/JavaBeans#JavaBean_conventions)。其餘的應該是顯而易見的。 –

+1

@jlordo儘管字符串比較是以錯誤的方式進行的,但代碼甚至不會編譯,因爲他試圖訪問私有變量。 – cesarse

+0

這不是重複的。 – NINCOMPOOP

回答

1

First comp ilation錯誤:

System.out.println ("Type: " + type + "\t" + "Make: " + make); 

Product沒有make實例變量。其子類GolfHat聲明變量。子類繼承超類的非私有成員,它不會以其他方式工作。

邏輯錯誤:

if (type=="Glove"){ 

    } 

這是比較字符串內容的錯誤方式。改用equals()方法。

if ("Glove".equals(type)){ 

    } 
0

您應該添加一個覆蓋toString方法您golfHat

public class GolfHat extends Product 
{ 
    public String toString() 
    { 
     // you can use make here 
    } 
} 
0

Golfhat是產品的一個子類。產品一無所知,不應該知道。 你可以從inheritance tutorial開始閱讀