Reputation: 357
Currently learning about Java and I have a question about making a subclass from an abstract class. I have this:
public abstract class Bike
{
private int cost;
public Bike(){}
public abstract void displayCost();
}
public class SportsBike extends Bike
{
private int topSpeed();
???
}
public class CasualBike extends Bike
{
private int brakeSpeed();
???
}
public void main()
{
SportsBike b1 = new SportsBike(???);
CasualBike b2 = new CasualBike(???);
}
How would I have the constructor for both sportsBike and casualBike so that they would have their own information?? I have read things about @super and such but I am not sure how to implement it. Would @override work if I have multiple class inheriting one class?
Upvotes: 1
Views: 3209
Reputation: 1050
This is a simple example that you can play around to see how constructors work, and how super class constructors are called automatically even if you don't explicitly call them:
public class Parent {
protected int parentVariable;
public Parent(){
parentVariable=1;
System.out.println("parent no-argument constructor");
}
public Parent(int value) {
System.out.println("parent int constructor");
parentVariable = value;
}
public int getParentVariable() {
return parentVariable;
}
}
public class Child extends Parent {
private int childVariable;
public Child() {
// Call super() is automatically inserted by compiler
System.out.println("child no-argument constructor");
childVariable = 99;
}
public Child(int value, int childValue){
// Explicit call to parent constructor
super(value);
System.out.println("child int constructor");
childVariable = childValue;
}
public int getChildVariable() {
return childVariable;
}
}
public class Driver {
public static void main(String[] args)
{
Child c1 = new Child();
Child c2 = new Child(3,199);
System.out.println(c1.getParentVariable());
System.out.println(c2.getParentVariable());
System.out.println(c1.getChildVariable());
System.out.println(c2.getChildVariable());
}
}
Upvotes: 1
Reputation: 1133
I am assuming that cost
is common for both CasualBike
and SportsBike
.
Use super keyword to call these two classes and form objects of them.
public class SportsBike extends Bike
{
SportsBike(int cost){
super(cost);
}
}
and your abstract class should be like :
public abstract class Bike
{
private int cost;
public Bike(cost){
this.cost=cost;
}
}
Upvotes: 1