Oop 3
Oop 3
In Java, the concept of inheritance allows the users to create classes and use
the properties of existing classes. A few important terminologies associated
with the concept are:
The new class created is called a sub-class while the inherited class is termed
a parent class.
As the name suggests, this type of inheritance occurs for only a single class.
Only one class is derived from the parent class. In this type of inheritance, the
properties are derived from a single parent class and not more than that. As
the properties are derived from only a single base class the reusability of a
code is facilitated along with the addition of new features
2. Multi-level Inheritance
3. Hierarchical Inheritance
The type of inheritance where many subclasses inherit from one single class is
known as Hierarchical Inheritance.
Polymorphism
It is one of the basic feature of object-oriented programming paradigm which is
used to implement different operation with the same function
If the child class object calls the method, the child class method will override
the parent class method. Otherwise, if the parent class object calls the
method, the parent class method will be executed.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
Rules For Method Overriding
The access modifier can only allow more access for the overridden
method.
We can call the parent class method in the overriding method using
the super keyword.
class Parent {
void show(){
System.out.println("parent class method");
}
class Child extends Parent {
void show(){
super.show();
System.out.println("child class method");
}
public static void main(String args[]){
Parent ob = new Child();
ob.show();
}
}
Output: parent class method
child class method
class OverloadingExample{
int add(int a,int b){return a+b;}
int add(int a,int b,int c){return a+b+c;}
}
The main advantage of using method overloading in Java is that it gives us the
liberty to not define a function again and again for doing the same thing. In the
below example, the two methods are basically performing division, so we can have
different methods with the same name but with different parameters. It also helps
in compile-time polymorphism.
public class Div{
public int div(int a , int b){
return (a / b); }