Java reserved words: super, final

super

super is a Java reserved word that is used to access member variables or methods of a superclass that is obscured by a subclass. Access the parent class’s member variables or methods as follows:

super.ObjectVariable
super.MethodName(parameter)

You can also use super to call the superclass constructor.

super(parameter)
class D1 {
	int x = 1000;

	void display() {
		System.out.println("The display() method of the superclass D1.");
	}
}

class D2 extends D1 {
	int x = 2000;

	void display() {
		System.out.println("The display() method of subclass D2.");
	}

	void write() {
		this.display();
		super.display(); //Execute the display() of the superclass(D1)
		System.out.println("Object x value of class D2: " + x);
		System.out.println("Object x value of class D1: " + super.x); //Get the x value of the superclass (D1)
	}
}

class InheritanceSuper {
	public static void main(String args[]) {
		D2 d = new D2();
		d.write();
	}
}
super use example

final

The Java reserved word final is available for three purposes.

  • 1. Can be used as an attribute variable of an object to be used as a constant.
  • 2. You can prevent the subclass from being overridden by appending ‘final’ to the method.
  • 3. Add the class with ‘final’ to prevent the class from having subclasses.

final makes security and design clear. In other words, attaching a final to a method or class that does not need access can block access at its source.

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest Post