In Java, the super keyword is used to refer to the parent class of a subclass, and is used to call a method or constructor from the parent class.
Here's an example:
class Animal { public void makeSound() { System.out.println("Some sound"); } } class Cat extends Animal { @Override public void makeSound() { System.out.println("Meow"); } public void printSound() { super.makeSound(); // Calls makeSound() method from parent class } } public class Main { public static void main(String[] args) { Cat myCat = new Cat(); myCat.makeSound(); // Outputs "Meow" myCat.printSound(); // Outputs "Some sound" } }
In this example, the Animal class has a makeSound() method that outputs "Some sound". The Cat class extends the Animal class and overrides the makeSound() method to output "Meow". The Cat class also has a printSound() method that calls the makeSound() method from the parent class using the super keyword.
When an instance of the Cat class is created and the makeSound() and printSound() methods are called, the appropriate sound is output for each method. The makeSound() method outputs "Meow", which is the behavior of the Cat class. The printSound() method calls the makeSound() method from the parent class using the super keyword, which outputs "Some sound", which is the behavior of the Animal class.
The super keyword can also be used to call a constructor from the parent class.
Here's an example:
class Animal { private int age; public Animal(int age) { this.age = age; } public int getAge() { return age; } } class Cat extends Animal { private String name; public Cat(String name, int age) { super(age); // Calls the constructor of parent class this.name = name; } public String getName() { return name; } } public class Main { public static void main(String[] args) { Cat myCat = new Cat("Fluffy", 2); System.out.println("Name: " + myCat.getName()); System.out.println("Age: " + myCat.getAge()); } }
In this example, the Animal class has a constructor that takes an age parameter, which is set to a private instance variable. The Cat class extends the Animal class and has a constructor that takes a name parameter and an age parameter. The super keyword is used to call the constructor of the parent class, passing the age parameter.
When an instance of the Cat class is created with a name and an age, the appropriate values are set for each instance variable. The getName() and getAge() methods are called to retrieve the name and age of the cat, which are output to the console.