gpt4 book ai didi

java - 从 Java 中的抽象类创建子类

转载 作者:行者123 更新时间:2023-11-30 02:39:07 26 4
gpt4 key购买 nike

目前正在学习 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 会起作用吗?

最佳答案

这是一个简单的示例,您可以尝试一下以了解构造函数如何工作,以及如何自动调用父类(super class)构造函数,即使您没有显式调用它们:

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());
}

}

关于java - 从 Java 中的抽象类创建子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42289473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com