Interface in Java

HOME

In this tutorial, I’ll explain about Interfaces in Java.

What is Interface?

An interface is a group of related methods with empty bodies (abstract methods).

  1. All the methods in Interface are public and abstract. 
  2. A class can implement more than one interface.
  3. An interface can extends another interface or interfaces 
  4. A class that implements interface must implements all the methods in interface. To implement interface use implements keyword.
  5. The variables declared in an interface are public, static & final by default.
  6. Java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance .

Syntax of Interface

interface test {
//declare methods which are abstract by default
//declare variables which are public, static, final by default
}

Relationship between Class and Interfaces

Below is an example of implementation of Interface. I have declared a class as Interface which have two abstract methods.

public interface MyInterface {

	// Abstract methods
	public void method1();

	public void method2();
}

Interface Implementation

public class InterfaceTest implements MyInterface {

	public void method1() {
		System.out.println("Implementation of Method 1");
	}

	public void method2() {
		System.out.println("Implementation of Method 2");
	}

	public static void main(String[] args) {
		MyInterface interTest = new InterfaceTest();
		interTest.method1();
		interTest.method2();

	}
}

Output

Implementation of Method 1
Implementation of Method 2

Multiple Interface

In the below example, Interface 2 extends Interface 1 and class implements Interface 2.

Interface 1

public interface Infa1 {
	public void method1();

}

Interface 2

public interface Infa2 extends Infa1 {
	public void method2();

}

MultipleInterfaceTest Class

public class MultipleInterfaceTest implements Infa2 {

	public void method1() {
		System.out.println("Implementation of Method 1");
	}

	public void method2() {
		System.out.println("Implementation of Method 2");
	}

	public static void main(String[] args) {

		Infa2 obj = new MultipleInterfaceTest();
		obj.method1();
		obj.method2();
	}

}

Output

Implementation of Method 1
Implementation of Method 2

Multiple Inheritance

Interface supports multiple Inheritance. Here, there are two interfaces which are implemented in class MultipleInheritanceTest.

Interface 1

public interface Infa1 {
	public void method();

}

Interface 2

public interface Infa2 {
	public void method();

}

MultipleInheritanceTest Class

public class MultipleInheritanceTest implements Infa1, Infa2 {

	public void method() {
		System.out.println("Implementation of Method ");
	}


	public static void main(String[] args) {
		MultipleInheritanceTest test = new MultipleInheritanceTest();
		test.method();
	}

}

Output

Implementation of Method

Advertisement

Abstraction in Java

HOME

In this tutorial, I’ll explain about abstraction in Java.

What is Abstraction?

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

There are two ways to achieve abstraction in java

  1. Abstract class
  2. Interface

What is an Abstract Class?

A class which is declared as abstract is known as an abstract class.

  1. It can have abstract and non-abstract methods.
  2. It needs to be extended and its method is implemented.
  3. It cannot be instantiated.
  4. It can have constructors and static methods also.
  5. It can have final methods which will force the subclass not to change the body of the method.
  6. An abstract class is a class that contains at least one abstract method.
  7. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

Example of Abstract Class

abstract class Test
{
}

What is Abstract Method?

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract int test(int a, int b);

Below is an example of abstraction.

Abstract Class

//Abstract Class
public abstract class Bank {

	// Abstract method
	abstract void getRateOfInterest();
}

SubClass1

//Subclass (inherit from Bank)
public class SBI extends Bank {

	// The body of getRateOfInterest is declared here
	public void getRateOfInterest() {

		System.out.println("Interest Rate of SBI Bank :" + 5.3);

	}
}

SubClass2

//Subclass (inherit from Bank)
public class BOI extends Bank {

	// The body of getRateOfInterest is declared here
	public void getRateOfInterest() {

		System.out.println("Interest Rate of BOI Bank :" + 4.1);

	}

}

Test Class

public class AbstractionTest {

	public static void main(String[] args) {

		Bank bank1 = new SBI();
		bank1.getRateOfInterest();

		Bank bank2 = new BOI();
		bank2.getRateOfInterest();

	}

}

Output

Interest Rate of SBI Bank :5.3
Interest Rate of BOI Bank :4.1

Abstract class can have a data member, constructor, abstract method, non abstract method and even main() method.

Below is an example where the abstract class has both abstract method as well as non abstract method.

public abstract class Bike { // abstract class

	int x = 25; // Instance Variable

	Bike() // Constructor
	{
		int y = 10;

		System.out.println("Value of y :" + y);
		System.out.println("Bike is created");

	}

	abstract void run(); // abstract method

	void change_gear() // non abstract method
	{
		System.out.println("Gear is changed");
	}

}

SubClass

public class Trek extends Bike {

	void run() {
		System.out.println("Bike is running");
	}

}

Test Class

public class AbstractionDemoTest {

	public static void main(String[] args) {

		Bike bike = new Trek();
		bike.run();
		bike.change_gear();

		System.out.println("Value of x :" + bike.x);

	}
}

Output

Value of y :10
Bike is created
Bike is running
Gear is changed
Value of x :25

Advantages of Abstraction

  1. It reduces the complexity of viewing the things.
  2. Avoids code duplication and increases reusability.
  3. Helps to increase security of an application or program as only important details are provided to the user.

Polymorphism in Java

HOME

In this tutorial, I’ll explain about Polymorphism in Java. It is one of the four concepts of OOPs. It is a concept where we can perform a single action in multiple ways. Poly means many and morphs means form. Polymorphism allows us to define one interface and have multiple implementations. An example of polymorphism is that there are different forms of communication like call, sms, picture messages, etc.

There are 2 types of polymorphism:-

  1. Method Overloading in Java – This is an example of compile time (or static polymorphism)
  2. Method Overriding in Java – This is an example of runtime time (or dynamic polymorphism)

Complie Time Polymorphism

It is also known as static polymorphism. Method Overloading is an example of static polymorphism. It is a feature that allows a class to have more than one method having the same name, if their argument lists are different. Error if any occur, resolved during compile time.

Below is an example of static polymorphism.

public class Calculation {

	void sum(int a, int b) {
		System.out.println("Sum of 2 numbers :" + (a + b));
	}

	void sum(int x, int y, int z) {
		System.out.println("Sum of 3 numbers :" + (x + y + z));
	}

}

public class PolymorphismTest {

	public static void main(String[] args) {

		Calculation cal = new Calculation();
		cal.sum(10, 5);
		cal.sum(2, 6, 4);

	}
}

Output

Sum of 2 numbers :15
Sum of 3 numbers :12

Dynamic Polymorphism

It is also known as Dynamic Method Dispatch. In this call to overridden method happens at the runtime. This type of polymorphism is achieved by Method Overriding. Declaring a method in sub class which is already present in parent class is known as method overriding. 

Below is an example of dynamic polymorphism

Parent Class

public class Bank {

	 //Overridden method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of parent class");
		System.out.println("Interest Rate of Bank :" + 0);

	}
}

Child 1 Class

public class BOI extends Bank {

    // Overriding method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of child 1 class");
		System.out.println("Interest Rate of BOI Bank :" + 4.1);

	}

}

Child 2 Class

public class BofA extends Bank {

    // Overriding method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of child 2 class");
		System.out.println("Interest Rate of BofA Bank :" + 3.2);

	}

}

Child 3 Class

public class SBI extends Bank {

	// Overriding method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of child 3 class");
		System.out.println("Interest Rate of SBI Bank :" + 5.3);

	}
}

Test Class

public class StaticPolTest {

	public static void main(String[] args) {

		Bank bank1 = new Bank();
		bank1.getRateOfInterest();

		BOI bank2 = new BOI();
		bank2.getRateOfInterest();

		BofA bank3 = new BofA();
		bank3.getRateOfInterest();

		SBI bank4 = new SBI();
		bank4.getRateOfInterest();
	}

}

Output

getRateOfInterest() method of parent class
Interest Rate of Bank :0
getRateOfInterest() method of child 1 class
Interest Rate of BOI Bank :4.1
getRateOfInterest() method of child 2 class
Interest Rate of BofA Bank :3.2
getRateOfInterest() method of child 3 class
Interest Rate of SBI Bank :5.3

Points to note for Method Overriding:-

  1. The argument list of overriding method (method of subclass) must match the Overridden method(the method of parent class). The data types of the arguments and their sequence should exactly match.
  2. Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. 

Suppose, I have changed the access modifier of SBI class from public to protected and then run the StaticPolTest program. In that case, I’ll get a compile time error.

getRateOfInterest() method of parent class
Interest Rate of Bank :0
getRateOfInterest() method of child 1 class
Interest Rate of BOI Bank :4.1
getRateOfInterest() method of child 2 class
Interest Rate of BofA Bank :3.2
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot reduce the visibility of the inherited method from Bank

	at JavaDemo.Polymorphism.SBI.getRateOfInterest(SBI.java:6)
	at JavaDemo.Polymorphism.StaticPolTest.main(StaticPolTest.java:17)

Encapsulation in Java

HOME

Encapsulation in Java is a process of wrapping the data and code in a single unit. The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. It is one of the four important OOPs concept.

To achieve encapsulation in Java −

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.

The get method returns the variable value, and the set method sets the value.

Syntax of get method – method name starts with get followed by the variable name where first letter is capital.

Syntax of set method – method name starts with set followed by the variable name where first letter is capital.

Below is an example of encapsulation with two variables and their getter and setter method.

public class EncapsulationDemo {

	// private variables
	private String name;
	private int age;

	// getter method for age
	public int getAge() {
		return age;
	}

	// setter method for age
	public void setAge(int setAge) {
		this.age = setAge;

	}

	// getter method for name
	public String getName() {
		return name;
	}

	// setter method for name
	public void setName(String newName) {
		this.name = newName;
	}

}

The variables of the EncapsulationDemo class can be accessed using the following program −

public class EncapsulationTest {

	public static void main(String[] args) {

		//creating instance of the encapsulated class
		EncapsulationDemo encap = new EncapsulationDemo();

		//setting value in the age member 
		encap.setAge(25);
		
		//setting value in the name member 
		encap.setName("Terry");

		//getting value of the age and name member  
		System.out.print("Name : " + encap.getName() + " and Age :" + encap.getAge());

	}

}

Output

Name : Terry  and Age :25

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE’s are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.