My assignment calls for an abstract Snack class, then subclasses SaltySnack and Sugary Snack. Each object has a name, calories and cost. Now I need to actually create the objects and I am confused on how to do this. Here is what I have so far.
Hi Lynn. As far as I can tell, there is no need to redeclare all the methods in the two subclasses. The subclasses shouldn't change anything about their implementation. SugarySnack and SaltySnack are just empty (one could say useless) subclasses.
Do you know how to make instances of a class? For instance, you could declare a variable "crisps" and assign to it a new instance of the class SaltySnack, supplying a name, caloric value and cost to the constructor.
When I try to instantiate an object, I get a message that says my actual and formal arguments differ in length. I can't put anything in the parentheses, so how can I make the object? I am sorry I am so clueless.
This is how I am trying to instantiate SaltySnack s1 = new SaltySnack("popcorn", 230, .85);
Is this not right?
Stephan van Hulst
Joined: Sep 20, 2010
That's correct. The problem is that your SaltySnack class doesn't have an explicit constructor yet. Constructors are not inherited from super-classes. So you need to declare a constructor that has the same parameters as the superclass, and then passes the arguments to the super-class constructor. Have you learned about the "super" keyword yet?