Archive for June, 2013

Interface as reference data type in Java

So far, I hadn´t understood that interfaces can be used as data types in java. I discovered it while learning depency injection.
An interface in java is a valid referenca data type. If you want to use an interface as reference variabile, make sure your class implements it!

Here is the interface for any liquid container:

public interface LiquidContainer {

void fill(int ml);
void empty();
void wash();
void drink();

}

The class Glass implements the developed interfaced:

import static java.lang.System.out;

public class Glass implements LiquidContainer{

	@Override
	public void fill(int ml) {
		out.println("Glass filled with "+ml+"!");
	}

	@Override
	public void empty() {
		out.println("Your glass is now empty.");
	}

	@Override
	public void wash() {
		out.println("the glass has been washed.");
	}

	@Override
	public void drink() {
		out.println("you have drunk from a Glass.");
	}
}

Mug is another class implementing the interface:

import static java.lang.System.out;

public class Mug implements LiquidContainer {

	@Override
	public void fill(int ml) {
		out.println("Mug filled with "+ml+"!");
	}

	@Override
	public void empty() {
		out.println("Your Mug is now empty");
	}

	@Override
	public void wash() {
		out.println("Your mug has been washed.");
	}

	@Override
	public void drink() {
        out.println("You have drunk from a mug.");
	}
}

Then we can define two classes: Superman and Batman mugs extending Mug, without specifying what they implement:

import static java.lang.System.out;

public class SupermanMug extends Mug{

	LiquidContainer liquidContainer;

	@Override
	public void fill(int ml) {
		out.println("Superman Mug filled with "+ml+"!");
	}

	@Override
	public void empty() {
		out.println("superman Mug is now empty.");
	}

	@Override
	public void wash() {
		out.println("Superman Mug has been washed.");
	}

	@Override
	public void drink() {
		out.println("you have drunk from a Superman Mug!");
	}
}

And finally a Breakfast class:

public class Breakfast {

LiquidContainer lc;

	static void drinkFromObject(LiquidContainer lc){
		lc.drink();
	}

	public static void main(String args[]){

		SupermanMug sm=new SupermanMug();
		BatmanMug bm=new BatmanMug();
		Glass glass=new Glass();
		Mug mug=new Mug();

		drinkFromObject(glass);
		drinkFromObject(mug);
		drinkFromObject(sm);
		drinkFromObject(bm);
	}
}

The “drinkFromObject” methods work for any liquid container objects, no matter what the class inheritance is, because it takes an interface (LiquidContainer) as reference data type parameter. The resulte is:

you have drunk from a Glass.
You have drunk from a mug.
you have drunk from a Superman Mug!
you have drunk from a Batman Mug!

Subtle, isn´t it?

Categories
Links: