unit 3
unit 3
https://beginnersbook.com/2013/03/inheritance-in-java/
https://www.geeksforgeeks.org/inheritance-in-java/
www.javatpoint.com/
• You can create new classes that are built upon existing classes.
• When you inherit from an existing class, you can reuse methods
and fields of the parent class.
• you can add new methods and fields in your current class also.
• Inheritance represents the IS-A relationship which is also known
as a parent-child relationship.
• For Code Reusability.
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 3
• Inheritance is a process of defining a new class based on
an existing class by extending its common data members
and methods.
• Inheritance allows us to reuse of code, it improves
reusability in your java application.
• The biggest advantage of Inheritance is that the code
that is already present in base class need not be
rewritten in the child class.
• This means that the data members(instance variables)
and methods of the parent class can be used in the child
class as.
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 4
Terms used in Inheritance
• Class: A class is a group of objects which have common properties.
It is a template or blueprint from which objects are created.
class Animal{
void eat(){ System.out.println("eating"); }
}
class Dog extends Animal{
•Definition:
•When a class is declared as final, it cannot be subclassed
/inherited
Example:
Output:
ROI: 9.15
ROI: 9.7
class Student{ }
class Test{
public static void main( String args[ ] )
{
// declaring an object 's' of the student class
student s = new student( ) ;
// checking whether s is an instance of the student class
Boolean str = s instanceof student;
// printing the string value
System.out.println( str ) ;
}
Output : true
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 59
• An object of subclass type is also a type of parent class.
class Teacher { }
public class Student extends Teacher
{
public static void main( String args[ ] )
{
// declaring the object of the class 'Student'
Student s = new Student( ) ;
// checking whether the object s is the instance of the parent class ' Teacher '
well as subclass
• is-a relation "A Car is-a Vehicle" sounds right Natural for Car to inherit
from mammal
• has-a relation"A car is-a(n) engine" sounds wrong Not natural to use