“super” vs “this” in Java

Super Keyword and Usage

  • refer to the immediate parent class instance variable.
  • to invoke immediate parent class constructor (here we are using the super() method)
  • invoke immediate parent class method

Refer to the immediate parent class instance variable

class Parent {
String attribute = "Parent Attribute";
}


class Child extends Parent{
String attribute = "Child Attribute";

void method(){
System.out.println(attribute);
}
}
public class SuperExampleClass {
public static void main(String[] args) {
Child child = new Child();
child.method();

}
}
class Parent {
String attribute = "Parent Attribute";
}


class Child extends Parent{
String attribute = "Child Attribute";

void method(){
System.out.println(super.attribute);
}
}
public class SuperExampleClass {
public static void main(String[] args) {
Child child = new Child();
child.method();

}
}

What is a constructor?

The super() method used to invoke immediate parent class constructor

class Parent {
Parent(){
System.out.println("Parent Class Constructor");
}
String attribute = "Parent Attribute";
}


class Child extends Parent{
Child(){
super();
System.out.println("Child Class Constructor");
}
String attribute = "Child Attribute";

void method(){
System.out.println(attribute);
}
}
public class SuperExampleClass {
public static void main(String[] args) {
Child child = new Child();

}
}
class Parent {
Parent(){
System.out.println("Parent Class Default Constructor");
}
Parent(int a, int b){
System.out.println("Parent Class Parameterized Constructor");
}
}


class Child extends Parent{
Child(){
System.out.println("Child Class Default Constructor");
}
Child(int a, int b){
super(a, b);
System.out.println("Child Class Parameterized Constructor");
}

}
public class SuperExampleClass {
public static void main(String[] args) {
Child child = new Child(1,2);

}
}

Invoke immediate parent class method

super.methodParent();

This Keyword and Usage

public class Student {

int id;
String name;
String address;

public Student(int id, String name, String address) {
id = id;
name = name;
address = address;
}

public void print(){
System.out.println("STUDENT DETAILS: ID: "+ id + " Name: "+ name + " Address: " + address);
}

public static void main(String[] args) {
Student student = new Student(1, "Kasun", "Colombo");
student.print();

}

}
public Student(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kasun Dissanayake

Kasun Dissanayake

Software Engineer at IFS R & D International (Pvt) Ltd || Former Software Engineer at Pearson Lanka || Former Associate Software Engineer at hSenid Mobile