opencodez

Object oriented concepts – Java

Q: What are basic OOPS Concepts?

A: x Inheritance : When a child class acquires all the methods and properties of parent class it is called inheritance. Java supports inheritance either using classes or interfaces.

Encapsulation: In above class, we have declared id as private and defined two methods that will act as mutator and accessors for this id propert. Thus we are encapsulateing objects property and  methods with in an object, keeping it safe from outside world.

Polymorphism: In below scenario, we have added 2 declaration of a function add() to child class, one is for adding  integers and another is to add float values. This kind of behavior when same name is used to perform different tasks as per the parameters passed to it is called polymorphism.

class Parent
{
	private int id;
	public Parent()
	{
	   aMethod();
	}

	public void aMethod()
	{
	   System.out.println("I am in Parent");
	}

	public int getId()
	{
	  return this.id;
	}

	public void setId(int id)
	{
	  this.id = id;
	}
}

class Child extends Parent
{
	public Child()
	{
	  bMethod();
	}

	public void bMethod()
	{
	  System.out.println("I am in Child");
	}

	public void add(int a, int b)
	{
	}

	public void add(float a, float b)
	{
	}
}

In java polymorphism is achieved by function overloading. It is also called Compile time Polymorphism. Compile decides at compile time that which version of function is called depending up on the parameters passed.

function overriding is also type of polymorphism, some times it is called Run time polymorphism, because the methods version is decided depending on the reference type of object at run time.

x

Important Notes:

x

x

public void aMethod(int a, long b)
{
   System.out.println("int a, long b");
}
public void aMethod(long a, int b)
{
   System.out.println("long a, int b");
}

For above methods to be polymorphic you need to use them as x

someobject.aMethod(1,2L);
someobject.aMethod(1L,2);
//someobject.aMethod(1,2); //compile time error
//someobject.aMethod(2,1); //compile time error