可以一个 Java 类对象作为另一个类中的状态变量吗?

huangapple go评论74阅读模式
英文:

Can a java class object be a state variable in another class?

问题

让我们假设我在Java中有一个Car类,然后我创建另一个名为ElectricCar的类。在我的ElectricCar类中,可以将Car对象作为状态变量吗?

英文:

Let's say I have a Car class in Java and then I make another class called ElectricCar. Can a Car object be a state variable in my ElectricCar class?

答案1

得分: 2

简而言之:是的。试试看:

    class Car {
    }

    class ElectricCar {
        Car myCar = new Car();
    }
英文:

Simply put: yes. Try it:

class Car {
}

class ElectricCar {
    Car myCar = new Car();
}

答案2

得分: 1

是的,这很常见:

class Car {
}

class ElectricCar {
    private final Car car;

    ElectricCar(Car car) {
        this.car = car;
    }
}
英文:

Yes; and it's quite common:

class Car {
}

class ElectricCar {
    private final Car car;

    ElectricCar(Car car) {
        this.car = car;
    }

}

huangapple
  • 本文由 发表于 2020年5月30日 00:04:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/62090130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定