Java继承和变量

时间:2014-03-04 06:38:53

标签: java inheritance constructor

我知道这是非常基本的但是我无法用一种不熟悉的语言拼凑起来。我正在将UML映射到Java代码,继承正在抛弃我。我有一个像这样的ERD:

Animal
----------------------------
-color: int
-weight: int
----------------------------
+ getColor() : int
+ getWeight(): int
----------------------------
         ^(Inheritance Triangle)
         |
         |
----------------------------
Dog
----------------------------
-breed: string
----------------------------
+ getBreed()
----------------------------

当然是狗IS-A动物,我可以从狗类等调用getColor。我的问题是关于变量,特别是构造函数。当我实现这个时,我有

public class Animal 
{
    private int color;
    private int weight;

    public Animal(int c, int w)
    {
        color = c;
        weight = w;
    }
   ...
}

public class Dog extends Animal
{
    private string breed;

    public Dog()
    {
        breed = "Shelty";
    }
}

我的问题是,在狗类中使用颜色和重量的正确方法是什么?看看UML,我知道我可以在dog实体中添加颜色和重量,但我知道这是可选的。我还会在狗类中拥有私人颜色和重量属性吗?我会调用Animal构造函数(抛出错误)这里的表格是什么?

4 个答案:

答案 0 :(得分:9)

Dog类的职责应该是初始化它添加的 new 功能,并让超类初始化Dog类继承的所有属性。

你可以这样做:

public class Dog extends Animal
{
    private String breed;

    public Dog(int color, int weight, String breed)
    {
        super(color,weight); //let superclass initialize these.
        this.breed = breed;
    }
}

答案 1 :(得分:3)

您使用关键字super。

public Dog(int c, int w){
    super(c,w);
    breed = "Shelty";
}

答案 2 :(得分:2)

除了manish的回答, 您还可以编写NoArg构造函数来提供默认初始化值。

public class Dog extends Animal
{
    private String breed;

    public Dog(int color, int weight, String breed)
    {
        super(color,weight); //let superclass initialize these.
        this.breed = breed;
    }

    // Default initialization if required
    public Dog() {
        this ( 0, 0, "Shelty")
    }
}

答案 3 :(得分:1)

public class Dog extends Animal
{
    private String breed;

    //Declaring default constructor is a good practice

    public Dog() 
    {
      //Some default values
       int color=3,weight =8;
       super(color,weight);
       this.breed = "pug";
    }

    public Dog(int color, int weight, String breed)
    {
       super(color,weight); 
       this.breed = breed;
    }
}