[!INDEX]

  1. Definition
  2. Calling the Superclass Constructor (super()), animal - dog - main
  3. Approach
  4. Accessing Superclass Method (super.methodName()) animal - dog - main
  5. Approach
  6. Accessing Superclass Field (super.fieldName) animal - dog - main
  7. Approach

1. Definition

[!NOTE]

Uses of the super keyword in Java:

  1. To call the superclass constructor.
  2. To access a superclass method.
  3. To access a superclass field.

2. Calling the Superclass Constructor (super())

[!NOTE]

class Animal {
    Animal() {
        System.out.println("Animal constructor called");
    }
}
class Dog extends Animal {
    Dog() {
        super();  // Calls the constructor of Animal class
        System.out.println("Dog constructor called");
    }
}
public class Main {
    public static void main(String[] args) {
        Animal a = new Animal();    
        Dog dog = new Dog();  // When Dog is created, Animal's ct is also called
        System.out.println("main method called ");       
    }
}
Animal constructor called
Animal constructor called
Dog constructor called
main method called

3. Approach

[!approach]

  1. subclass ct contains super() keywords

4. Accessing Superclass Method (super.methodName())

[!NOTE]

class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}
class Dog extends Animal {
    @Override
    void makeSound() {
        super.makeSound();  // Calls the makeSound() method of the Animal class
        System.out.println("Dog barks");
    }
}
public class Main1 {
    public static void main(String[] args) {
        Animal a1 = new Animal();
        a1.makeSound();
        Dog dog = new Dog();
        dog.makeSound();  // Calls Dog's makeSound(), which also calls Animal's makeSound()
        System.out.println("main ");
    }
}
Animal makes a sound
Animal makes a sound
Dog barks
main

5. Approach

[!approach]

  1. same as above but, super.mt name

6. Accessing Superclass Field (super.fieldName)

[!NOTE]

class Animal {
    String name = "Animal";
}
class Dog extends Animal {
    String name = "Dog";  // Hides the name field of Animal class

    void displayNames() {
        System.out.println("Parent class name: " + super.name);  // Refers to the Animal class's name field
        System.out.println("Child class name: " + this.name);    // Refers to the Dog class's name field
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.displayNames();
    }
}
Parent class name: Animal
Child class name: Dog

7. Approach

[!approach]

  1. same as above