-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

3 Answers3

1

First compilation error:

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

Product doesn't have the make instance variable. Its subclass GolfHat declares the variable . Subclass inherits non-private members of a superclass, it doesn't work the other way round.

Logical error :

if (type=="Glove"){

    }

This is an erroneous way of comparing String contents . Use equals() method instead.

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

    }
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

You should add a override toString method to your golfHat

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

Golfhat is a subclass of Product. Product knows nothing about make and shouldn't know. You can start reading from inheritance tutorial

Tala
  • 8,888
  • 5
  • 34
  • 38