Declaring Methods  «Prev 


Java-instance program

The Instance program illustrates the use of this and super. The Instance constructor invokes the display() method in the following ways:

display(this.s); 
display(super.s); 
this.display(s); 
super.display(s); 

This results in the following output being displayed:
this: this 
this: super 
this: this 
super: this                

The Instance program

class Instance extends SuperClass {
  String s = "this";

  public static void main(String[] args) {
    new Instance();
  }
  
  Instance() {
    display(this.s);
    display(super.s);
    this.display(s);
    super.display(s);
  }

  void display(String s) {
    System.out.println("this: " + s);
  }
}

class SuperClass {  
  String s = "super";

  void display(String s) {
    System.out.println("super: " + s);
  }
}