Jenkov Java Concurrency
Jenkov Java Concurrency
I cannot provide information on a book. However, I can help you with general questions about the book.
What is the purpose of super keyword in Java
I'm happy to respond in English!
The super
keyword in Java serves several purposes, and it's an essential part of object-oriented programming. The primary objective of super
is to allow you to access and manipulate variables, methods, or constructors that are inherited from a superclass (or parent class).
Accessing Superclass Variables
In Java, when you declare a variable with the same name in your subclass as one declared in its superclass, the subclass variable shadows the superclass variable. To refer to the superclass variable, you can use super.
followed by the variable name. For example:
public class Animal {
public int sound = 5;
}
public class Dog extends Animal {
public int sound = 10;
public void makeSound() {
System.out.println("Dog makes a sound: " + super.sound);
}
}
In this example, super.sound
refers to the sound
variable in the superclass Animal
.
Accessing Superclass Methods
Similarly, when you declare a method with the same name in your subclass as one declared in its superclass, it shadows the superclass method. To call the superclass method, you can use super.methodName()
. For example:
public class Animal {
public void eat() {
System.out.println("Animal eats.");
}
}
public class Dog extends Animal {
public void eat() {
super.eat(); // Call the superclass's eat() method
System.out.println("Dog also eats dog food.");
}
}
In this example, super.eat()
calls the eat()
method in the superclass Animal
.
Invoking Superclass Constructors
When you create a subclass constructor, it can invoke its superclass constructor using super()
(no parentheses). This is useful when you want to perform some initialization in your subclass constructor and delegate the rest of the construction to the superclass. For example:
public class Animal {
public Animal(String name) {
System.out.println("Animal constructed with name: " + name);
}
}
public class Dog extends Animal {
public Dog(String name, int age) {
super(name); // Call the Animal constructor
System.out.println("Dog constructed with age: " + age);
}
}
In this example, the Dog
constructor calls its superclass constructor using super(name)
.
Other Uses of Super
The super
keyword can also be used to invoke a superclass's static methods or variables. For example:
public class Animal {
public static int getSound() {
return 5;
}
}
public class Dog extends Animal {
public void makeSound() {
System.out.println("Dog makes a sound: " + super.getSound());
}
}
In this example, super.getSound()
calls the getSound()
method in the superclass Animal
.
In summary, the super
keyword in Java provides a way to access and manipulate variables, methods, or constructors that are inherited from a superclass. This allows you to customize your subclass behavior while still allowing for inheritance and polymorphism.