目前正在学习Java,我有一个关于从抽象类创建子类的问题。我有这个:
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(???);
}
我如何拥有sportsBike和casualBike的构造函数,以便他们拥有自己的信息?我已经阅读了有关@super等的内容,但我不确定如何实现它。如果我有多个类继承一个类,那么@override会工作吗?
答案 0 :(得分:1)
我假设cost
和CasualBike
都SportsBike
很常见。
使用super关键字来调用这两个类并形成它们的对象。
public class SportsBike extends Bike
{
SportsBike(int cost){
super(cost);
}
}
你的抽象类应该是:
public abstract class Bike
{
private int cost;
public Bike(cost){
this.cost=cost;
}
}
答案 1 :(得分:1)
这是一个简单的例子,您可以使用它来查看构造函数的工作方式,以及如果您没有显式调用它们,如何自动调用超类构造函数:
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());
}
}