пятница, 5 января 2024 г.

super keyword in Java

    The 'super' keyword is used to refer to the immediate parent class object. It can be used to call the superclass methods, access superclass fields, and invoke the superclass constructor. The 'super' keyword is often used in the context of inheritance.

Here are the main uses of the super keyword in Java:

  • Accessing Superclass Fields:
You can use 'super' to access fields from the superclass if a subclass has a field with the same name.

class Animal {
String name = "Animal";
}

class Dog extends Animal {
String name = "Dog";

void printNames() {
System.out.println(name); // prints "Dog"
System.out.println(super.name); // prints "Animal"
}
}

  • Invoking Superclass Methods:
You can use 'super' to invoke methods from the superclass. This is particularly useful when a subclass overrides a method, and you still want to call the superclass version.

class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}

class Dog extends Animal {
void makeSound() {
super.makeSound(); // calls the makeSound method of the superclass
System.out.println("Bark");
}
}

  • Invoking Superclass Constructor:
The 'super' keyword is also used to invoke the superclass constructor from the subclass constructor. It must be the first statement in the subclass constructor.

class Animal {
Animal() {
System.out.println("Animal constructor");
}
}

class Dog extends Animal {
Dog() {
super(); // invokes the constructor of the superclass (Animal)
System.out.println("Dog constructor");
}
}


Комментариев нет:

Отправить комментарий