0

I was wondering if it was possible for example to create automaticly 2 objects from a class into a new class, and then use a main class create a new object of the new class you just created.

For example:

Public class Trafficlight(){
 String color;

 public trafficLight(Somecolor){
  this.color = Somecolor;
 }

}


public class CrossRoad(){
 public CrossRoad(){
 trafficLight trafficLightNr1 = new  trafficLight("green");
  trafficLight  trafficLightNr2 = new  trafficLight("red");
 }
}

Public class main
{
   public static void main(String[] args) {
    CrossRoad SomeCrossRoad = new CrossRoad();
    CrossRoad SomeOtherCrossRoad = new CrossRoad();   
    }
}

Ps: if there are some mistakes in my syntax, i just wrote it fast. I'm just curious if this is possible to create something like this.

4

1 回答 1

1

是的,这是可能的,但是您需要将这些对象存储在类中,否则当构造函数的范围完成时它们将丢失。

public class CrossRoad(){
    TrafficLight trafficLightNr1;
    TrafficLight trafficLightNr2;
    public CrossRoad(){
        trafficLightNr1 = new TrafficLight("green");
        trafficLightNr2 = new TrafficLight("red");
    }
}
于 2013-06-04T21:13:05.250 回答