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

Inheritance in Java

    Inheritance is a fundamental concept in object-oriented programming (OOP) languages like Java. It allows a class to inherit properties and behaviors (fields and methods) from another class, promoting code reuse and establishing a relationship between classes. In Java, the "extends" keyword is used to implement inheritance.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

Here's a basic example to illustrate inheritance in Java:

// Parent class (also called superclass)
class Animal {
String name;

public Animal(String name) {
this.name = name;
}

public void eat() {
System.out.println(name + " is eating.");
}

public void sleep() {
System.out.println(name + " is sleeping.");
}
}

// Child class (also called subclass)
class Dog extends Animal {
public Dog(String name) {
// Call the constructor of the superclass (Animal)
super(name);
}

public void bark() {
System.out.println(name + " is barking.");
}
}

public class InheritanceExample {
public static void main(String[] args) {
// Creating an instance of the Dog class
Dog myDog = new Dog("Buddy");

// Accessing methods from the superclass (Animal)
myDog.eat();
myDog.sleep();

// Accessing methods from the subclass (Dog)
myDog.bark();
}
}

Keep in mind that Java supports single inheritance, meaning a class can only extend one superclass. However, it can implement multiple interfaces to achieve a form of multiple inheritance.


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

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