在Java中从抽象类创建子类
目前正在学习Java,我有一个关于从抽象类生成子类的问题。我有这个:在Java中从抽象类创建子类,java,inheritance,abstract-class,Java,Inheritance,Abstract Class,目前正在学习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 exten
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(???);
}
我将如何拥有SportBike和casualBike的构造器,以便他们拥有自己的信息??我读过关于@super之类的东西,但我不知道如何实现它。如果我有多个类继承一个类,@override会起作用吗?我假设
成本
对于休闲车
和运动自行车
都很常见
使用super关键字调用这两个类并形成它们的对象
public class SportsBike extends Bike
{
SportsBike(int cost){
super(cost);
}
}
您的抽象类应该如下所示:
public abstract class Bike
{
private int cost;
public Bike(cost){
this.cost=cost;
}
}
这是一个简单的示例,您可以通过它了解构造函数是如何工作的,以及如何自动调用超级类构造函数,即使您没有显式调用它们:
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());
}
}
构造函数参数对于SportsBike和CasualBike类都是通用的吗?只需添加要
SportsBike
和CasualBike
的构造函数,并在其中设置所需的内容。知道即使你不在子类构造函数中调用超类构造函数,它也会为你调用,但它会在子类构造函数之前执行,因此你可以根据自己的喜好初始化你的成员变量。那么,在SportsBike中初始化topSpeed是否有效?SportsBike(int-cost,int-speed){super(cost);topSpeed=speed;}如果子类或子类有自己的变量要初始化,它将如何工作?您只需使用子类/子类构造函数初始化变量,就像使用不扩展任何其他类的类一样(显然,除了隐式扩展Obect
)之外。我编辑了答案以显示一个简单的示例。感谢您提供的示例!