Search code examples
javanullsystem

How to use a object created in a subclass of a abstract class, in the abstract class


I have created a plane seat booking system via a brief that was provided by my university for a assignment. I am running into one main problem that I just can not figure out.

The brief states that the abstract class must have one abstract method and about 4 public methods. In both of the subclasses of the abstract class we have to initialize the array of objects (all plain seats). However, once they are initialized I do not know how I can send them back to the abstract class (which has a method that checks for unbooked plane seats, this is where I need the initialized seat object)

ArrayIndexOutOfBounds on a object that should be in bounds

The above link contains every single one of the classes and their code, I had a previous error which someone helped me fix and just thought it would be easier to link the full files here.

I just want to use the initialized array of objects (seats) created in a subclass of a abstract class, in the abstract class.

All input is greatly appreciated!


Solution

  • In the abstract class method(where you want to use the initialized array), you can just assume the array is already initialized. However, in the subclass, you cannot have another "Seat[][] newSeats;". So, just delete that in all sub-classes.

    A quick example is as following,

    //This will print 6 to the std output
    public class HelloWorld{
    
         public static void main(String []args){
            Child test = new Child();
            System.out.println(test.getArrFirst());
         }
    
    
         public static abstract class Parent{
            int[] abc;
    
            public int getArrFirst(){
                return abc[1];
            }
         }
    
         public static class Child extends Parent{
    
             public Child(){
                 abc = new int[10];
                 abc[1] = 6;
             }
         }
    }