Wednesday, March 8, 2017

Marker Interface in Java

In this article we will discuss about Marker Interface in Java,what is the use of Marker Interface and in which situation we used in Java.

What is Marker Interface:

Marker interface is an interface with no fields or methods.By implementing an interface if our objects will get some ability, Such type of interfaces are called "marker" or "tag interface".

Examples: Serializable interface,Cloneable interface and Remote interface

Use of Marker interface:

Marker interface is used to indicate something to compiler or JVM that the class implementing any of these would have some ability.The main purpose of Marker interface is to mark the class with a special meaning that can be used in a particular context.

For example:Serializable interface,this interface is used to mark serialization and deserialization of an object.When a class implements serialization,it informs that it can be serialized. The actual serialization is handled by ObjectInputStream and ObjectOutputStream class though.

Similarly cloneable interface,it is also used to mark the cloning operation.An object of a class which implements Cloneable interface is eligible for field copying of an object.For actual cloning,a class has to override clone() method in Object.


How to create user defined Marker interface:

To create our own Marker interface,you need to create an interface without any method and that is your marker interface. Client code can test whether an object is an instance of the marker interface and adapt it's behavior accordingly. The following examples says the marker interface.

Example 1:

interface student
{
}
class Mpcs implements student
{
public void Batch()
{
if(this instanceof Mpcs)
System.out.println("student is a MPCS Batch");
else
System.out.println("student is not a MPCS Batch");
}
}
public class TestClass
{
public static void main(String args[])
{
Mpcs m=new Mpcs();
m.Batch();
}
}

Output:
 




Example 2:

interface Deposit
{
}
interface Withdraw
{
}

class Money implements Deposit
{
static void  MoneyByDeposit()
{
System.out.println("Money is deposited");
}
}
class MoneyOne implements Withdraw
{
static void MoneyByWithdraw()
{
System.out.println("Money is withdrawn");
}
}
public class Minterface

{
public static void main(String []args)
{
Money.MoneyByDeposit();
MoneyOne.MoneyByWithdraw();
}
}

Output:

 







No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...