[英]Creating a subclass from an abstract class in Java
Currently learning about Java and I have a question about making a subclass from an abstract class. 目前正在学习Java,我有一个关于从抽象类中创建子类的问题。 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?? 我将如何为sportsBike和CasualBike构造函数,以便他们拥有自己的信息? I have read things about @super and such but I am not sure how to implement it. 我已经读过有关@super之类的东西,但是我不确定如何实现它。 Would @override work if I have multiple class inheriting one class? 如果我有多个继承一个类的类,@ override是否可以工作?
I am assuming that cost
is common for both CasualBike
and SportsBike
. 我假设cost
是两个常见的CasualBike
和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;
}
}
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.