Interfaces

From Knowledge Kitchen
Jump to navigation Jump to search


Overview

From Oracle's Java tutorials:

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces

Call-to-action

Why don't you put your notes on interfaces here? Use wiki syntax to make them look nice - send them to me.

The Oracle Java Tutorials offer some useful notes, if you refuse to read your textbook!

Student notes

Disclaimer: these notes have not been reviewed nor endorsed by your instructor. Some may contain factual inaccuracies.

Notes by S.P., Spring 2019

What are Interfaces?

Overview

Interfaces are class-like constructs that only contain constants, default methods, abstract methods, static methods, method signatures, and nested types. Interfaces can be seen as outlines that are meant to specify behaviors and capabilities for objects that can be both related and unrelated.

Interfaces are often compared to abstract classes, however there are differences in the usages of both. Interfaces cannot be instantiated and instead can only be implemented by classes or extended by other interfaces.

What's Inside an Interface

Though interfaces are known as an outline for methods to be defined by implementing classes, interfaces can have default and static methods: the only methods in an interface that can have method bodies. Default methods were added to interfaces so that changes could be made to an interface and implementing classes without requiring the rewriting of them. The static methods provide a level of security by not allowing implementing classes to override them.

Once a method signature is included in an interface, any class that implements the interface must define the specific method body for that method.

Some More Properties About Interfaces

When do you use classes versus interfaces? Scroll below to see some interface properties that make them similar to and different from classes.

How Interfaces are Different than Classes
  • Interfaces do not contain constructors
  • Interfaces do not contain instance fields
  • Interfaces are not extended, they are implemented by classes
  • You cannot instantiate an interface
How Interfaces are Similar to Classes
  • An interface can extended multiple interfaces
  • An interface can contain any number of methods
  • An interface is written in a file with a .java extension (and the byte code appears in a .class file)

Sample Code

When run, the following code will demonstrate how interfaces and classes that implement interfaces work...

//Please ignore the poor documentation for this code...be sure to use the proper Java Documentation that was taught in class

//First interface
public interface Interface_Ex {
    public final double pi = 3.14159265;
    public abstract void firstMethod();
    public abstract void secondMethod();
    
    public static void doSomething() {
        System.out.println("Doing something");
    }
    public default void doSomethignElse() {
        System.out.println("Doing something else");
    }
}

//Second interface which extends the first 
public interface Interface_Ex2 extends Interface_Ex{
    public abstract void thirdMethod();
}

//Class which implements the first interface
public class Class_Ex1 implements Interface_Ex{
    public int x = 56;
    public static final int FOO = 3;
    
    public static void doSomethingElse() {
        System.out.println("Class_Ex1 is doing something else");
    }
    public void foo() {
        System.out.println("Class_Ex1 foo");
    }
    public void firstMethod() {
        System.out.println("Class_Ex1 is implementing 'firstMethod'");
    }
    public void secondMethod() {
        System.out.println("Class_Ex1 is implementing 'secondtMethod'");
    }
}

Notes by A.K., Spring 2019

This page contains notes about the use of Interfaces in Java programming. Interfaces are simply the blueprints for making classes (they specify what a class does, but they don't specify how).

Concept

Interfaces are everywhere in our lives: a TV remote is an interface between your fingers and the electrical wiring beneath the buttons; the pedals on a bike are an interface between your feet and the gears.

In Java programming, interfaces are used in a very similar way.

Properties of interfaces:

  • They essentially allow for maximum abstraction.
  • Interfaces specify the public API, and any variables we introduce in them are virtually constant.
  • More importantly, interfaces, unlike custom classes from which we may instantiate certain objects, may only have static final attributes/variables declared in them.
  • Interfaces must have no constructors, and the methods within them must be declared abstract.
  • By default, interface methods are declared abstract and public.
  • By default, interface attributes are public, static, and final.

We cannot instantiate the interfaces themselves, but we can extend them into other interfaces, or implement them in custom classes.

Interface-Basics

Interfaces are their own data type in Java. Similarly to custom classes, they contain no main methods.

They are declared with the interface keyword, like this:

public interface Bicycle { //defining an interface for a bicycle
}
Bike-Example

Showing an example of defining an interface which will be later implemented by a bike (custom) class:

public interface Bicycle { //defining the bicycle interface

	public static final int MAX_GEAR = 6; //defining the maximum gear number of any bike

	public static final int MIN_GEAR = 1; //defining the minimum gear number of any bike

	//this method allows changes the rate of wheels spinning
	public abstract void cadence(int newRate);
	
	//this method allows to change the gear to some other one
	public abstract void gear(int newGear);

	//this method allows to increase the speed of the bike by a given amount
	public abstract void goFaster(int increase);

	//this method allows to apply brakes, and decrease speed by a given amount
	public abstract void pleaseBrake(int decrease); 
}

Once we defined the interface, lets make a bike class which will implement from it:

Note: the compiler will require that the methods defined in the Bicycle interface should be all implemented (overriden) in the Bike class, otherwise our program will not compile (if any of these methods should be missing from the class implementing it):

public class Bike implements Bicycle { //defining the Bike class, which implements the Bicycle interface

    private int cadence = 0; //defining the attributes of any object instantiated from this class
    private int speed = 0;
    private int gear = 1;

    public Bike(){ //no-args constructor for a Bike object
    	System.out.println("A new bike is created!");
    }

    public void cadence(int newRate) { //setter for cadence
         this.cadence = newRate;
    }

    public void gear(int newGear) { //setter for gears
        if (!(newGear > MAX_GEAR) && !(newGear < MIN_GEAR)){
        	this.gear = newGear;
        }
    }

    public void goFaster(int increase) { //setter for going faster
    	if (increase >= 0){
        	this.speed = this.getSpeed() + increase;   
    	}
    }

    public void pleaseBrake(int decrease) { //setter for decreasing the speed
    	if (decrease >= 0){
        	this.speed = this.getSpeed() - decrease;
    	}
    }

    public void showDetails() { //method which out-prints the cadence, speed, and gear
         System.out.println("Cadence:" + getCadence() + " Speed:" + getSpeed() + " Gear:" + getGear());
    }

    public int getSpeed(){ //getter for speed
    	return this.speed;
    }
    
    public int getGear(){ //getter for gears
    	return this.gear;
    }
    
    public int getCadence(){ //getter for cadence
    	return this.cadence;
    }
}

We can then instantiate the bike object and access all of its properties:

public class HelloWorld{
	public static void main(String[] args){

	Bike cycle = new Bike(); //instantiating the 'cycle' object
	cycle.gear(2); //setting the gear
	cycle.goFaster(4); //increasing the speed
	cycle.pleaseBrake(1); //decreasing the speed
	cycle.cadence(100); //setting the rate of wheels spinning
	cycle.showDetails(); //out-printing the details of the object
	}
}
Multiple-Interface-Examples

Given the following declared interface:

public interface Bicycle { //defining an interface for a bicycle
}

We may also declare another one:

public interface Car { //defining an interface for a car
}

And then make a class that implements them both at the same time (note the syntax):

public class CarBike implements Bicycle, Car { //defining a class which implements both interfaces
	//the resulting class must contain all of the abstract methods from both of the interfaces implemented
}

The same may be done for extending multiple abstract interfaces into one.


What links here