Junior
Which elements of the Java language are responsible for inheritance?
sobes.tech AI
Answer from AI
- The
extendskeyword is used to indicate inheritance of a class from another class. - The
implementskeyword is used to indicate that a class implements one or more interfaces (behavior inheritance). - The
superkeyword is used to refer to members of the parent class (fields, methods, constructors). - The
abstractkeyword is used to create abstract classes and methods that must be implemented in subclasses. - The
finalkeyword can be used to prevent method overriding (final method) or class inheritance (final class). - Interfaces define a contract of methods that a class must implement. They allow multiple inheritance of types (but not implementation).
Example of using extends:
// Parent class
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
// Child class inheriting from Animal
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
Example of using implements:
// Interface
interface Swimmable {
void swim();
}
// Class implementing the interface
class Fish implements Swimmable {
@Override
public void swim() {
System.out.println("Fish is swimming");
}
}
Example of using super:
class Parent {
int value = 10;
void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
int value = 20;
void display() {
super.display(); // Call parent method
System.out.println("Child display " + super.value); // Access parent field
}
}
Example of using abstract:
// Abstract class
abstract class Shape {
// Abstract method (without implementation)
abstract double getArea();
}
// Concrete class inheriting from Shape and implementing the abstract method
class Circle extends Shape {
double radius;
@Override
double getArea() {
return Math.PI * radius * radius;
}
}
Example of using final:
class Base {
// Method that cannot be overridden
final void finalMethod() {
System.out.println("Final method");
}
}
// Class that cannot be inherited
final class CannotExtend {
// ...
}