In: Computer Science
What is the purpose of extending a class due to inheritance? Provide an example of extending a class due to inheritance. Provide the code, and explain the processes.
Simple Java Programming.
Purposes of Inheritance:
1. Code reusability (being able to use the code again)
2. Code structuring (packing right set of data and methods that resembles the real-life objects)
Sample Program
public class Main //Main class
{
public static void main(String[] args) //main method
{
Student student = new Student("Leonardo diCaprio", 21); //student object
Teacher teacher = new Teacher("Angelina Jolie", "B.Tech"); //teacher object
System.out.println("Student is "+student.name+" and teacher is "+teacher.name); //printing student and teacher names
}
}
class Person //person class
{
String name; //every person definitely has a name
Person(String name) //constructor for Person class
{
this.name = name;
}
}
class Student extends Person //Student class inheriting Person class because every student is a person and so student inherits all data and methods of person
{
int rollno; //extra data for a student is rollno
Student(String name, int rollno) //constructor for Student class
{
super(name); //reusability of Person constructor and name data of Person class (main reason for inheritance)
this.rollno = rollno;
}
}
class Teacher extends Person //Teacher class inheriting Person class because every teacher is a person and so teacher inherits all data and methods of person
{
String qualification; //extra data for a teacher is qualification
Teacher(String name, String qualification) //reusability of Person constructor and name data of Person class (main reason for inheritance)
{
super(name);
this.qualification = qualification;
}
}
Sample program Screenshot
Output Screenshot
Each and everything is explained clearly in the comment section of the code.
Thank you! Hit like if you like my work.