Java超类从子类获取参数值

时间:2015-12-12 10:47:36

标签: java subclass superclass

问题是:

1)如何将子类参数值提供给超类?

2)我想为collection.sort取名字(From subclass),如this.model.compareTo(other.model)。但是,我不知道如何获得"姓名"来自子类的值并执行collection.sort。

**写公共int compareTo是否正确(Car other,Taxi other2)??? **

以下是代码:

 public class Car implement comparable <Car>() 
 {
 private string model;
 private int price;


 public car(String model , int price)
{
   this.model=model;
   this.price=price;
 } 

    ............some getmethod here..........

  public int compareTo (Car other)  
  {
        ** Want to sort by name , like this.model.compareTo(other.model)**
  }


 }

Taxi.java:

public class taxi extends Car ()
{
     private string name;
     public taxi (String model , int price, String name)
     { 
         super(model, price);
         this.name = name; 
     }
       ......some getmethod here..........
}

1 个答案:

答案 0 :(得分:0)

您可以通过在超类中创建子类的对象来使用子类值。 它也被称为委托。