Welcome to the fifth part of our Core Java series. In the last part, we discussed about Arrays, Sring and StringBuffer Class. If you are new, please checkout the previous parts. In this part, we’ll discuss obejct-oriented programming in Java. So Let’s get started.

If a problem is solved in terms of classes and objects, it is called object oriented programming.

Class

A class provides definition for an object. An object is known as an instance of the class. A class contains two parts - private part and public part.

In general, private part contains variables and it is not accessible to the user. Similarly, methods form public part of the class and public part of the class is accessible to the user.

Let’s take an example where we’ll create a class and use its objects.

class Money{
	private int rs;
	private int paise;

	public void set(int r, int p){
		rs = r;
		ps = p;
	}

	public void display(){
		System.out.println(rs + "." + paise);
	}
}

Save this file as Money.java Now let’s another class which will utilise this class.

class UseMoney{
	public static void main(String args[]){
		Money m;
		m = new Money();
		m.set(20,40);
		System.out.println("Amount is:");
		m.display();
	}
}

When we compile and run this file, it’ll create an object of Money class and set (20,40) values in its variables (rs,paise). When we call display method it’ll give the output values on the console.

Method Overloading

Method overloading is an example of compile time polymorphism that means same method name can be used with different number of arguments(One name many forms).

  • A class can contain any number of methods as long as their signatures are different. Signature is nothing but method name and arguments all together.
  • A class can contain multiple methods with same name as long as their arguments are different. It is called Method Overloading.
  • Either number of arguments must be different or type of arguments must be different or order of arguments must be different.

Let’s see an example -

class Calculator{
	public int sum(int a, int b){
		return a+b;
	}

	public int sum(int a, int b, int c){
		return a+b+c;
	}

	public float sum(float a, float b){
		return a+b;
	}

	public float sum(int a, float b){
		return a+b;
	}

	public float sum(floar a, int b){
		return a+b;
	}
}

class Application{
	public static void main(String args[]){
		Calculator calc = new Calculator();
		int x;
		float a;
		x = calc.sum(1,2);
		System.out.println(x);			// Output will be 3
		a = calc.sum(1.5F,2.7F);
		System.out.println(a);			// Output will be 4.2
	}
}

In this example, if we want to get the sum of more than 3 arguments we can use variable length arguments. Let’s see an example.

class Calculator{
	public int sum(int ... abc){
		int total = 0;
		for(int x=0; x<abc.length; x++)
			total += abc[i];
		return total;
	}
}
  • Only one variable length argument is allowed in a function and it should be last formal parameter.
public void method(String s, float a, int ... b){
	...
}
  • It reduces number of methods in a class if method overloading is being done on the basis of number of parameters.

this variable

this is a reference variable which refers to an object that has called the member function. this variable is created automatically so we don’t need to declare it. It is available in all the methods of the class except static methods.

class Money{
	private int rs;
	private int paisa;

	public void set(int rs, int paisa){
		this.rs = rs;			// it will set the value of private variables
		this.paisa = paisa;
	}
}	

Constructors

These are special methods that are called automatically when an object of the class if created. Constructors have same name as the class. They don’t have any return type not even void (If we define return type then it’ll be considered as a method.)

There are three types of constructors -

  1. Default Constructor - This constructor takes no arguments and it is called when an object is created without any explicit initialization. e.g.

Money m1 = new Money();

  1. Parameterised Constructor - It is called when an object is created and is initialized with some values at the time of creation. e.g.

Money m2 = new Money(100,20);

  1. Copy Constructor - It is called when an object is created and is initialized with some other object of the same class at the time of creation. e.g.

Money m3 = new Money(m2);

NOTE - If we don’t define any of the constructor than default constructor will be provided by Java. But if we define any of the constructors than Java will not provide any constructor.

  • A Constructor is called once for an object in its lifetime when it is created.

By using this() a constructor can be called from another constructor of the same class as a method name. A call to this() must be the first executable statement of the construction otherwise there will be compile time error.

class Point3D{
	private int x,y,z;

	public Point3D(int a, int b, int c){
		x = a;
		y = b;
		z = c;
	}

	public Point3D(int a, int b){
		this(a,b,0);
	}

	public Point3D(int a){
		this(a,0,0);
	}

	public Point3D(Point3D p){
		this(p.x, p.y, p.z);
	}
}
  • Only one this() can be called in one constructor.
  • Constructors cannot be recursive or cyclic. e.g.
public int Point3D(int a, int b){
	this(a,b);
}

Inheritance

Inheritance means to derive a class from another class. The derived class has features of base class plus its own additional functionality. In Java, we use extends keyword to inherit a class. For example -

class A{			// Super class
	int x,y;		// inherited members
	...
	...
}

class B extends A 		// sub class
{
	int z;
	...
	...
}
  • An inherited member is that member of super class that is accessible to the methods of the sub class.
  • Super class variables that are not inherited(i.e. private variables) still form part of the sub-class object and we can refer to them indirectly through the public methods that have been inherited.

Example -

class A{
	private int x;
	public void setX(int a){
		x = a;
	}

	public void showX(){
		System.out.println(x);
	}
}

class B extends A{
	private int y;
	public void setXY(int a, int b){
		setX(a);
		y = b;
	}

	public void showXY(){
		showX();
		System.out.println(y);
	}
}

class demo{
	public static void main(String args[]){
		B b = new B();
		b.setXY(1,2);
		b.showXY();
	}
}

Method Overriding

If super class and sub class both have methods with same name, same argument lists and same return types, it is called method overriding.

  • If super class and sub class both have methods with same name and same argument list then their return type must also be same otherwise it would lead to a compile time error.

  • Instance methods can override instance methods and static methods can override static methods.

  • While overriding a method, the overridden method in the sub class can be less restricted(protected to public) but it cannot be more restrictive(protected to private)(compile time error).

NOTE - Multiple inheritance of classes are not allowed in Java.

class A extends B,C 	// error
{
	...
}

Abstract Methods and Classes

If a method has no definition then it is called abstract method and it must be declared using a keyword abstract otherwise it would lead to a compile time error.

If a class includes one or more abstract methods then it is called an abstract class and it must be declared using the keyword abstract otherwise it would be a compile time error.

  • When a class extends an abstract class then it must define all the abstract methods.

Example -

abstract class Animal{
	abstract public void speak();
	abstract public void move();
}

class Dog extends Animal{
	public void speak(){
		System.out.println("Bark!!!");
	}
	public void speak(){
		System.out.println("Run!!!");
	}
}

class Cat extends Animal{
	public void speak(){
		System.out.println("Meow!!!");
	}
	public void speak(){
		System.out.println("Walk!!!");
	}
}
  • Abstract methods cannot be private since private methods are never inherited.
  • Abstract methods/class cannot be final.
  • Constructors cannot be abstract because constructors are never inherited.

Interface

An interface is known as a collection of abstract methods and constants.

  • A class is inherited whereas an interface is implemented.
  • In an interface methods are public and abstract by default and variables are public, static and final by default.
  • We can not create an object of an interface but we can create a reference variable. This reference variable can refer to objects of all those classes that implements the interface.
  • In an abstract class some of the methods might be defined but in interface all the methods are abstract.
  • An interface can extends another interface unlike classes where multi inheritance is not allowed.

Example -

interface Animal{
	void speak();
	void move();
	int NO_OF_LEGS = 4;
}

class Dog implements Animal{
	public void speak(){
		System.out.println("Bark");
	}
	public void move(){
		System.out.println("Runs");
	}
}

class Cat implements Animal{
	public void speak(){
		System.out.println("Meow");
	}
	public void move(){
		System.out.println("Walks");
	}
}

class Home{
	public static void main(String args[]){
		System.out.println("Our pets have " + Animal.NO_OF_LEGS + " legs");

		Animal a;		// interface reference variable
		a = new Dog();
		a.speak();		// Output: Bark
		a.move();		// Output: Runs

		a = new Cat();
		a.speak();		// Output: Meow
		a.move();		// Output: Walks
	}
}
interface x{
	void a();
	void b();
}

interface y{
	void c();
	void d();
}

interface z extends x,y{		// Contains methods of x and y both
	void e();
	void f();
}

class Demo implements z{
	// All 6 methods has to be defined
}

That’s all for now. Now it’s your turn to try what you learned in this blog. Happy Coding :)