How to Access Hidden Fields of Superclass Using the super Keyword - Java Object Oriented Design

Java examples for Object Oriented Design:Inheritance

Description

How to Access Hidden Fields of Superclass Using the super Keyword

Demo Code

class MySuper {/*from   ww  w . j av  a  2 s  .c om*/
  protected int num = 100;
  protected String name = "Edith";
}

class MySub extends MySuper {
  // Hides the num field in MySuper class
  private int num = 200;

  // Hides the name field in MySuper class
  private String name = "Mary";

  public void print() {
    // MySub.num
    System.out.println("num: " + num);

    // MySuper.num
    System.out.println("super.num: " + super.num);

    // MySub.name
    System.out.println("name: " + name);

    // MySuper.name
    System.out.println("super.name: " + super.name);
  }
}

public class Main {
  public static void main(String[] args) {
    MySub a = new MySub();
    a.print();
  }
}

Result


Related Tutorials