Java Super and Final
Java Super and Final
class Parent
{
final void display()
{
System.out.println("Parent Class");
}
}
{
System.out.println("Child Class");
}
}
}
class Dog extends Animal // Error: cannot subclass final class
{
}
super keyword
Super keyword is used for
To Call superclass constructor Syntax:- super();
To Call superclass method Syntax:- super.method();
To Access superclass variable Syntax:- super.variable;
class Animal
{
Animal()
{
System.out.println("Animal constructor");
}
}
Output:
Animal constructor
Dog constructor
If a method in the subclass overrides a method from the parent class, you
can still call the parent’s version using super.
class Animal
{
void sound()
{
System.out.println("Animal makes sound");
}
}
Output:
class Animal
{
String type = "Generic Animal";
}
void printType()
{
System.out.println(super.type); // Output: Generic Animal
System.out.println(this.type); // Output: Dog
}
}
Abstract keyword
The abstract keyword in Java is used with classes and methods to
define a blueprint that must be implemented by subclasses. It plays a
key role in abstraction
abstract Class
but it can have both abstract methods (without a body) and normal
methods (with a body).
Animal a = new Animal(); // Error: Cannot create object the type Animal
abstract Method