2013-06-20 50 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开始阅读