super in java

Previous
Next

super:

thissuper
It is a keywordIt is a keyword
It is a pre-defined non static variableIt is a pre-defined non static variable
It is used to access current object(class) functionalityIt is used to access Parent object(class) functionality from the Child
It must be used only in non-static contextIt must be used only in non-static context
It holds object addressIt doesn’t hold any object address
class Parent
{
	void fun()
	{
		System.out.println("Parent's fun");
	}
}
class Child extends Parent
{
	void fun()
	{
		System.out.println("Child's fun");
	}
	void access() // non static area
	{
		this.fun();  // access Child class fun
		super.fun(); // access Parent class fun
	}
}
class Check
{
	public static void main(String[] args) 
	{
		Child c = new Child();
		c.access();
	}
}

Super doesn’t holds Parent object address:

class Parent
{
	// empty
}
class Child extends Parent
{
	Child()
	{
		System.out.println("Child's address : " + this);
		// System.out.println("Parent's address : " + super);  // Error : 'super' doesn't holds address
	}
}
class Check
{
	public static void main(String[] args) 
	{
		new Child();
	}
}

Why ‘super’ doesn’t holds Parent address?

  • We can access the complete functionality of all the objects in the hierarchy using single address (Child’s).
  • There is no separate Parent object to hold the address by super keyword.
  • We can say ‘super’ is the sub pointer to ‘this’ keyword and it is used to access Parent functionality from Child.
Previous
Next

Add Comment

Courses Enquiry Form