1

I'm learning inheritance in java. While writing small code where I'm learning we cannot access private members of superclass in subclass.

Here is my code:

class A {
    int i;
    private int j;

    void setij(int x, int y) {

        i = x;
        j = y;
    }

    class B extends A {

        int b;

        void sum() {

            b = i + j;
        }
    }

When I create a new class in eclipse, am not able to create an object of sublcass B in class A.

class mainclass{

            public static void main(String args[]){
                 B object = new B(); ----error


            }
        }

    }

Error says class B needs to be created.

May I know why is happening ..? Its happening not a problem but I want to solve and understand the logic why it was happened.

Thanks

LearnJava
  • 372
  • 1
  • 4
  • 16

2 Answers2

2

That's because class B is present inside class A, it needs to be created outside of A, e.g.:

class A {
    int i;
    private int j;

    void setij(int x, int y) {

        i = x;
        j = y;
    }   
}

class B extends A {

     int b;
     void sum() {
        b = i + j;
     }
 }

With this code, class B (and A) will be accessible from all the classes from inside the package. If you want these classes to be accessible from outside the current package then you need to create these classes in separate files and mark them as public.

Here's more on access modifiers for classes.

Upate

If you want to define class B as an inner class in A then you will need the instance of enclosing class (A in our case) to access B, e.g.:

class A {
    int i;
    private int j;

    void setij(int x, int y) {

        i = x;
        j = y;
    }   

    class B extends A {

        int b;
        void sum() {
           b = i + j;
        }
    }
}

Now, to instantiate B, you need to do the following:

A a = new A();
B b = a.new B(); 

And of course, same rules as access modifier will apply to inner class instance (except the fact that inner class will be able to access private members of enclosing class),

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
1

This is because an instance of class B must relate to an instance of class A. So you must first create an instance of class A, then the instance of class B:

    A a = new A();
    a.setij(1,2);
    B b = a.new B();
    b.setij(3,4);
    b.sum();
    System.out.println(b.b);

(the result is 5 in case you were wondering)

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24