Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Declarations and Access Control - this and super

this (JLS §15.8.3)

  • this is an Object-Oriented Programming (OOP) operator
  • it is used to refer to the current instance of an object
  • it can be used in the body of a class constructor to refer to the object being created
  • it can be used in the body of an instance method or initializer to refer to the object whose method is being executed
  • it cannot be used in a static method or initializer
  • most commonly appears in constructors
  • can be used to explicitly call another constructor
  • when used in a constructor it must be the first statment in the constructors body
class Super {

    int x;
    int y;

    Super(){

        System.out.println("Super object being created.");

	}
	
    Super( int x, int y ) {

        this();             // call no-arg constructor

        this.x = x;

        this.y = y;    

    }

}	
	

super

  • super is an Object-Oriented Programming (OOP) operator
  • used to call a constructor declared in a classes superclass
  • commonly used in constructors and to access hidden fields or invoke overridden methods in the superclass
  • if used in a constructor, must be the first statment in constructor body
Remember
  • Constructors are not inherited!
 class Subclass extends Super {
    int w;

    Subclass(){
        this(0,0,0);        // call 3-param constructor
    }

    Subclass( int x, int y ) {
        this(x,y,0);        // call 3-param constructor
    }

    Subclass( int x, int y, int w ) {    

        super(x,y);         // call superclass constructor
        this.w = w;
    }
}
 
Remember
  • You cannot use this() and super() in the same constructor.
Subclass( int x, int y, int w) {

        this();

        super(x,y);         // compile-error

    }

Example Code

TestThisAndSuper.java

Access Modifiers Special Modifiers this and super Scope Inheritance Access Control