-6

Hi guys I'm creating a program that is a shoping cart and I'm trying to create a toString() method.

This is my GolfHat class

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;

    }

and my product class is this

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";

    }

it wont let me use the make variable, I think it wont let me do this cause my variables are private however for part of my assesment i need to show a example of encaspulation and im struggerling to see where else I'll be able to do it

4

3 回答 3

1

第一次编译错误:

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

Product没有make实例变量。它的子类GolfHat声明了变量。子类继承了超类的非私有成员,反之则不行。

逻辑错误:

if (type=="Glove"){

    }

这是比较字符串内容的错误方式。改用equals()方法。

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

    }
于 2013-06-20T18:28:12.633 回答
0

Golfhat 是 Product 的子类。产品对制造一无所知,也不应该知道。您可以从继承教程开始阅读

于 2013-06-20T18:31:03.347 回答
0

你应该添加一个覆盖toString方法到你的golfHat

public class GolfHat extends Product 
{
    public String toString ()
    {
        // you can use make here
    }
}
于 2013-06-20T18:30:01.007 回答