Interfaces in Java

Alright I tend avoid using interfaces but here is skeleton example on how to code one in Java. Anyway here is the summary about interfaces from the Java docs:

  • An interface defines a protocol of communication between two objects.
  • An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions.
  • A class that implements an interface must implement all the methods declared in the interface.
  • An interface name can be used anywhere a type can be used.

http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html

In this skeleton code I just made an interface around a boolean value. You don’t define the methods of the interface but just reference them.

public interface StateInterface {
	 boolean toggle(); //Switches the boolean value and returns the new state
	 void turnOff(); // Sets the boolean value to false
	 void turnOn();  // Sets the boolean value to true
	 boolean get(); // Returns the boolean value
}

The next part is how you add the interface to a class object. The keyword here is “implements”. We have to define each method in the interface but we can also add some extra ones if we want. Since my class object is just a dump wrapper class around a Boolean value this example doesn’t do much.

public class State implements StateInterface {

	private boolean state;
	
	public State(){
		this.state = false;
	}
	
	public State(boolean state){
		this.state = state;
	}
	
	@Override
	public boolean toggle() {
		if(this.state)
			this.state = false;
		
		else if(!this.state)
			this.state = true;
			
		return this.state;
	}

	@Override
	public void turnOff() {
		this.state = false;
	}

	@Override
	public void turnOn() {
		this.state = true;
	}
	
	@Override
	public boolean get(){
		return this.state;
	}
}

Also, here is the simple test case on how to run it.

public class testState {
	
	public static void main(String[] args) {
		State s = new State();
		System.out.println("Current state: " + s.get() );
		System.out.println("Toggling state: " + s.toggle() );
		
		s.turnOff();
		System.out.println("Turned off: " + s.get());
		
		s.turnOn();
		System.out.println("Turned on: " + s.get() );
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s