2017-02-17 37 views
1

当前正在学习Java,我有一个关于从抽象类中创建子类的问题。我有这个:从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

是对于类SportBike和CasualBike常见的构造函数参数吗? –

+1

只需将您想要的构造函数添加到“SportsBike”和“CasualBike”中,并设置您想要的任何内容。要知道,即使你不在子类构造函数中调用超类构造函数,它也会被调用,但它会在子类构造函数之前执行,所以你可以随意初始化你的成员变量。 –

回答

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

} 
+0

如果子或子类有自己的变量进行初始化,它会如何工作? –

+0

您只需使用子/子类构造函数初始化变量,就像使用不扩展任何其他类的类一样(显然,除了隐式扩展'Obect')之外。我编辑了答案来展示一个简单的例子。 –

+0

谢谢你的例子! –

1

我假设cost对于CasualBikeSportsBike都是通用的。

使用super关键字来调用这两个类并形成它们的对象。

public class SportsBike extends Bike 
{ 
    SportsBike(int cost){ 
     super(cost); 
    } 

} 

和你的抽象类应该是这样的:

public abstract class Bike 
{ 
    private int cost; 

    public Bike(cost){ 
this.cost=cost; 
} 
} 
+0

那么,这个工作是否会在SportsBike中初始化topSpeed? SportsBike(int cost,int speed) { super(cost); topSpeed =速度; } –