Social Programmer
Social Programmer

Reputation: 167

Inner Class and Constructors

I want to create a class , which will have the same inner one , to be more specific something like this :

class PassengerComponent extends PlaneComponent
{   
   PassengerComponent InnerPC ;
   int inner ; // checks if PassengerComponent has an inner class

The passengerComponent inherits from :

class PlaneComponent
{
   String Description ;
}

The problem is that the inner class should be filled randomly , which means sometimes the passenger component will have an inner one and sometimes not! The way I am trying to do it , is the following :

        int random = (int )(Math.random() * 1 + 0 );
        if( random == 0)
        {
           PassengerComponent PC1 = new PassengerComponent("Passenger Component #1" , 0);    
        }
        else
        {
           PassengerComponent PC1 = new PassengerComponent("Passenger Component #1" , 1); 
        }

       PC1.ready_check(Sc, Cg);

While the passenger constructor is the following :

    public PassengerComponent( String D , int i)
    {
      Description = D ;
      System.out.println( " PassengerComponent: " + Description + " Has Been Created ");
      switch (i) {
        case 0:
            InnerPC = new PassengerComponent( " Inner Passenger Component #1 " , 2 );
            inner = 1 ;
            break;
        case 1:
            inner = 0 ;
            break ;
        case 2:
            break;
        default:
            break;
       }
    }
  }

The constructors are called and the output messages seems to be ok , but when PC1.ready_check is being called , compiler cant find PC1 , which i created ! (ready_check dont have any problems for anyone wondering)

Sorry for long question , any ideas ?

Upvotes: 1

Views: 130

Answers (1)

Spotted
Spotted

Reputation: 4091

It has nothing to do with inner classes or PassengerComponent, only with variable scope.

Since PC1 is declared inside the if/else block, it's only known within this block.

If you want to use PC1 after the if/else block, declare it one level above:

int random = (int )(Math.random() * 1 + 0 );
PassengerComponent PC1;
if( random == 0)
{
    PC1 = new PassengerComponent("Passenger Component #1" , 0);    
}
else
{
    PC1 = new PassengerComponent("Passenger Component #1" , 1); 
}

PC1.ready_check(Sc, Cg);

Upvotes: 1

Related Questions