Java Inheritance Member Access

Introduction

A subclass cannot access the private members from its superclass.

In a class hierarchy, private members remain private to their class.

// Create a superclass.
class A {/*from w w  w  .ja va  2 s  .  c  om*/
  public int i; 
  private int j; // private to A

  public void setij(int x, int y) {
    i = x;
    j = y;
  }
}

// A's j is not accessible here.
class B extends A {
  int total;

  void sum() {
    total = i + j; // ERROR, j is not accessible here
  }
}

public class Main {
  public static void main(String args[]) {
    B subOb = new B();

    subOb.setij(10, 12);

    subOb.sum();
    System.out.println("Total is " + subOb.total);
  }
}



PreviousNext

Related