Question:

I’m just starting out learning Java, and have come across a error that I cannot find the solution to.

by  |  earlier

0 LIKES UnLike

Can any one help? I KNOW it’s a real basic one, but it has me stumped.

My class has a superclass where I need to pass name, cost and size. The constructor in the subclass is as follows:-

/**

* Constructor for objects of class MilkBeverage, including variables of Super class (name,cost and size)

*/

public MilkBeverage(String milkName,float milkCost,char milkSize,String milkFlavour)

{

super(milkName,milkCost,milkSize);

flavour = milkFlavour;

name = "milkshake";

cost = milkCost;

size = milkSize;

option = 0;

}

When I initiate a new object I’m using:-

/**

* Main method of the MilkBeverage

*

* @param none

* @return none

*/

public static void main(String[] args)

{

MilkBeverage wotDrink = new MilkBeverage(name,cost,size,flavour); ß-------- Error here

wotDrink.director();

}

/**

The error I get on compilation is non-static variable name cannot be referenced from a static context.

I realise this, but if I leave the new MilkBeverage empty, I then get an error saying cannot find symbol – constructor MilkBeverage()

Can someone help out and let me know how this SHOULD be written?

Many thanks

 Tags:

   Report

3 ANSWERS


  1. In this line:

    MilkBeverage wotDrink = new MilkBeverage(name,cost,size,flavour);

    You reference four variables. You haven't defined any local variables with those names, so the compiler thinks you're trying to access the class variables with those names, which you can do from a static context like the main() method.


  2. if you pay me ill help....

  3. you have to define the name, cost, size, and flavour variables that you pass to the MilkBeverages constructor.

    The reason you can't call MilkBeverages() is that you haven't defined a constructor with no parameters.  When you write a class, then a default constructor is given to you that takes no parameters, but as soon as you write you're own constructor, the default constructor is no longer given.

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.