Java继承和变量

Java继承和变量,java,inheritance,constructor,Java,Inheritance,Constructor,我知道这是非常基本的,但我很难用一种不熟悉的语言把这些片段组合起来。我正在将UML映射到Java代码中,继承让我感到困惑。我有这样一个ERD: Animal ---------------------------- -color: int -weight: int ---------------------------- + getColor() : int + getWeight(): int ---------------------------- ^(Inheritanc

我知道这是非常基本的,但我很难用一种不熟悉的语言把这些片段组合起来。我正在将UML映射到Java代码中,继承让我感到困惑。我有这样一个ERD:

Animal
----------------------------
-color: int
-weight: int
----------------------------
+ getColor() : int
+ getWeight(): int
----------------------------
         ^(Inheritance Triangle)
         |
         |
----------------------------
Dog
----------------------------
-breed: string
----------------------------
+ getBreed()
----------------------------
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;
    }
}
当然狗是动物,我可以从狗类中调用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实体中添加颜色和权重,但我知道这是可选的。我会在dog类中也有一个私有的颜色和重量属性吗?我会调用动物构造器(抛出错误)这里的正确形式是什么?

您使用关键字super

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

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

你可以这样做:

Animal
----------------------------
-color: int
-weight: int
----------------------------
+ getColor() : int
+ getWeight(): int
----------------------------
         ^(Inheritance Triangle)
         |
         |
----------------------------
Dog
----------------------------
-breed: string
----------------------------
+ getBreed()
----------------------------
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;
    }
}

除了曼尼什的回答, 还可以编写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")
    }
}

您想从Dog类设置类Animal属性的值,还是想在Dog类中访问它?我们可以知道再次提供相同ans的原因吗?@KishanSarsechaGajjar这可能是因为您在我发布答案的同一时间编辑您的答案。