Inheritance
Inheritance in Java
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit the properties and methods of another class. It promotes code reusability and establishes a natural hierarchy between classes.
Basic Concepts
- Class: A blueprint for creating objects. It defines properties (fields) and behaviors (methods) that the objects created from the class can have.
- Superclass (Parent Class): The class whose properties and methods are inherited.
- Subclass (Child Class): The class that inherits the properties and methods from another class.
How Inheritance Works
In Java, inheritance is achieved using the extends
keyword. The subclass inherits all non-private members (fields and methods) from the superclass.
public class Student {
String name;
int age;
void display1()
{
System.out.println("Name : "+name);
System.out.println("Age : "+age);
}
}
public class Teacher extends Student{
String qualification;
void display2(){
display1();
System.out.println("Qualification : "+qualification);
}
}
public class Main {
public static void main(String[] args) {
Teacher obj = new Teacher();
obj.name = "Anisul Islam";
obj.age = 30;
obj.qualification = "Bsc In CSE";
obj.display2();
}
}
Comments
Post a Comment