I’m trying to create an object using a constructor from a subclass but I can’t assign values to that object in the subclass Constructor.
Here is the superclass.
public class Bike
{
String color = "";
String type = "";
int age = 0;
public static void main (String [] args)
{
}
public Bike (String s, int i) // Constructor
{
color = s;
age = i;
}
public void PrintBike ()
{
if (type == "")
{
System.out.print(" You didn't give the proper kind of bike.");
}
else
{
System.out.print(" Your bike is a " + type + " bike. \n");
}
}
}
This is the subclass.
public class BikeAdv extends Bike
{
private String type;
public BikeAdv (String color, int age, String BikeType)
{
super (color, age);
type = BikeType;
}
}
Here is the class that calls the constructor.
public class Green
{
public static void main (String [] args)
{
Bike greenBike = new BikeAdv ("Green", 20, "Mountain");
greenBike.PrintBike();
}
}
When I run the class “Green”, the output is ” You didn’t give the proper kind of bike.” whereas I would expect to see “Your bike is a Mountain Bike”.
Thanks!
You have declared these attributes without explicit visibility:
Also, you have
typeredeclared inBikeAdv, that is probably an error (you don’t need to).If you want to have these attribute only accessible from its class, then you should declared them
private. But, in that case, you have to parametrize the constructor to be able to modify all of them. Or maybe create setters for them (be aware that this way you will grant accessibility from outside the class).If you want them to be unmodifiable from outside its class, but accessible from its subclasses, then declare them as protected:
As you can see, there are a lot of possibilities. Check them out here:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html