Monday, April 28, 2025

Java OO Tutorial - super Keyword in Java

In Java, super is a keyword that refers to the immediate parent class of a subclass. It is used to call a constructor, method, or variable of the parent class from within the subclass. 

class Primary {
	
	public void sameName() {
		System.out.println("I am from Primary Class");
	}
}

class Secondary extends Primary {
	
	public void sameName() {
		super.sameName();
		System.out.println("I am from Secondary Class");
	}	
}

public class Main {	
	
	public static void main(String[] args) {
		
		//Primary primObj = new Primary();
		//primObj.sameName();
		
		Secondary secObj = new Secondary();
		secObj.sameName();		
	}	
}

This Java program defines three classes: Primary, Secondary, and Main.

The Primary class has one method called sameName(), which simply prints the message "I am from Primary Class" to the console. 

class Primary {
    public void sameName() {
        System.out.println("I am from Primary Class");
    }
}

The Secondary class extends the Primary class and overrides the sameName() method. Inside the sameName() method of the Secondary class, the super keyword is used to call the sameName() method of the parent class, and then it prints the message "I am from Secondary Class" to the console. 

class Secondary extends Primary {
    public void sameName() {
        super.sameName();
        System.out.println("I am from Secondary Class");
    }
}

The Main class contains the main() method, which creates an object of the Secondary class using the new keyword and assigns it to a reference variable named secObj. Then, it calls the sameName() method on the secObj reference variable. 

public class Main {
    public static void main(String[] args) {
        Secondary secObj = new Secondary();
        secObj.sameName();
    }
}

When the sameName() method of the secObj object is called, the following output will be printed to the console: 

I am from Primary Class
I am from Secondary Class

This shows that when a subclass overrides a method of its parent class, it can call the overridden method of the parent class using the super keyword, and then it can add its own functionality to the method.

In this example, the Secondary class added the message "I am from Secondary Class" to the output, but it first called the sameName() method of the parent Primary class to include its message "I am from Primary Class".

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...