Basic Concepts in Oops - 4

Hi everyone, this is the continuation of previous blog. Here, I am discussing some more topics on object oriented programming.

16) Polymorphism

Polymorphism in simple term means same name, but different functions. Polymorphism makes possible same functions to act different on different classes. It can happen in a same class or between different classes. In same class, sometimes there will be same function names with different parameters. Or if a class extends other class, there can be same function names with different implementation in both the classes.

17) Method Overloading

Method overloading occurs in the same class. Here, there will be functions with same name, but different arguments and return type. Following gives an example of method overloading.

class Vehicle
{
int vehilceId;
int registrationNum;
Vehicle(int a)
{
vehicleId=a;
registrationNum=a;
}
Vehicle(int a, int b)
{
vehicleId=a;
registrationNum=b;
}

}

Here, the constructor Vehicle is defined twice with different parameters.

18) Method Overriding

Method overriding occurs when a sub class overrides the method defined in the super class. Here, both subclass and superclass have the same method name. But when we instantiate an object of sub class, the method in the subclass will only be called. Following is an example of method overriding.


class Vehicle
{
int vehilceId;
int registrationNum;

Vehicle(int a, int b)
{
vehicleId=a;
registrationNum=b;
}
void printIt()
{
System.out.println("Inside Vehicle");
}
}

Class Car extends Vehicle
{
int yearOfProduction;
void printIt()
{
System.out.println(" Inside Car");
}
}

Class MainClass
{
public static void main(String args[])
{
Car benz = new Car();
benz.printIt();
}
}

The output is as follows: -

Inside Car

19) Method Signature

Method name together with the parameters is known as method signature. A method can have different signatures according to the different parameters.

20) Method visibility

Method visibility means controlling the visibility of the method in the class. There are four different types of visibility modifiers. They are

  • Public
If a class is declared public, it will be visible in all the other classes.
  • Default
If there is no access modifiers, then the class will only be visible in the same package. No subclass of that class can access the methods in the class.
  • Protected
If a class is declared Protected, then it will be visible in the same package and subclass of that class can access the methods in the class.
  • Private
If a class is declared Private, the methods in the class will only be visible to that class.

Hope this post gave you a clear idea about the topics mentioned here. Check my upcoming blogs for more about object oriented programming.

Thank you for reading the post. Suggestions/ Comments are always welcome.

Similar posts



Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++