Inheritance and Polymorphism
Inheritance and Polymorphism
what is it Inheritance?
what is it Inheritance?
The idea behind inheritance in Java is that 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. Moreover,
you can add new methods and fields in your current class also.
constructors
access control
Methods
Key words
this
final
Extends (To derive a class in java the keyword extend is used )
Super etc.
Types of inheritance
Single inheritance
When a class inherits another class, it is known as a single inheritance.
Multilevel inheritances
When there is a chain of inheritance, it is known as multilevel inheritance.
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance.
polymorphism
what is polymorphism
The word ‘polymorphism’ literally means ‘a state of having many shapes’ or ‘the
capacity to take on different forms’. When applied to object-oriented
programming languages like Java, it describes a language’s ability to process
objects of various types and classes through a single, uniform interface.
Example follows
Usage and rules of Java Method
Overriding
Usage
Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
Rules
The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
how to over lode
Class animal{
Public void add (){
// my code
}
Public void add(int a, int b){
//my code
}
Public int void add(){
// my code
}
Method overriding
Class Animal {
public void add() {
// my animal code
}
}
Class dog extends animal {