Interfaces and Abstract Classes are important instruments used in Java and other languages while building APIs.
The concept of an interface, as an agreement connecting different constructions, existed forever. Java made this concept official keyword in a programming language. The agreement must be completely implemented, otherwise a compiler will complain producing error messages.
In Java, an interface is similar to a class, but the interface defines method signatures. The method body or implementations will be defined in a class that implements that interface.
Note that the interface and each implementation class are separate files.
Example:
public interface MoneyManagement {
// just a signature: return type, the name of a method and possible arguments (in that case ? none)
public void manageMoney();
// there could be more method-signatures
}
Here are the implementation classes defined in different files (remember that each class or interface must be defined in a separate file with the same name and extension .java):
public class MotherMoneyManagement implements MoneyManagement {
// implementation of the manageMoney method
public void manageMoney() {
System.out.println("Spend wisely and SAVE!");
}
}
public class DaughterMoneyManagement implements MoneyManagement {
// implementation of the manageMoney method
public void manageMoney() {
System.out.println("Do more shopping!");
}
}
public class SonMoneyManagement implements MoneyManagement {
// implementation of the manageMoney method
public void manageMoney() {
System.out.println("Buy gifts for my girlfriend!");
}
}
Three classes implement the same interface in a different way.
These three classes have a common interface that can be considered as a parent. So these three classes are actually from the same family, a family of MoneyManagement.
We can say for any object of any of these three classes that this is an object type of MoneyManagement.
Why would we want to generalize this way?
The benefit is their polymorphic behavior. Here is an example of polymorphism, where we deal with an array of the MoneyManagement objects, where each object has a specific type MotherMoneyManagement, DaughterMoneyManagement or SonMoneyManagement.
Example:
public class TestMoneyManagement {
public static void main(String[] args) {
MoneyManagement mmm = new MotherMoneyManagement();
MoneyManagement dmm = new DaughterMoneyManagement();
MoneyManagement smm = new SonMoneyManagement();
// collect these objects into an array of MoneyManagement[] objects
MoneyManagement[] familyMoneyManagement = new MoneyManagement[] {mmm, dmm, smm};
for(int i=0; i < familyMoneyManagement.length; i++) {
// get the next element of the array
MoneyManagement mm = familyMoneyManagement[i];
// invoke the manageMoney() method
mm.manageMoney(); // each time it will produce a different message
}
}
}
Starting with Java 8, default and static methods may have implementation in the interface definition.
Interfaces can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
Interfaces as well as abstract classes cannot be instantiated. (See later about abstract classes.) You cannot create an object of an interface or an object of an abstract class. They both have not been defined completely. They are just templates.
Example: MoneyManagement mm = new MoneyManagement(); // will produce a compiler error
What is an abstract class?
Abstract class can have data and fully defined methods, but if at least one of the methods is not defined, does not have a body, this is an abstract class.
Example:
public abstract class Shape {
// data
private int[] coordinates; // x, y, z and maybe more coordinates to draw a shape
// methods
public int[] getCoordinates() {
return coordinates;
}
public void setCoordinates(int[] coordinates) {
this.coordinates = coordinates;
}
// method signature only, there is no body; this method makes the class abstract
public void draw(); // to be implemented in subclasses
}
public class Rectangle extends Shape {
public void draw() {
// implementation: using coordinates to draw a rectangle
}
}
public class Triangle extends Shape {
public void draw() {
// implementation: using coordinates to draw a triangle
}
}
public class TestShapes {
public static void main(String[] args) {
Shape r = new Rectangle();
// set coordinates for a rectangle
r.setCoordinates(new int[] {1,1, 2,2, 3,3, 4,4});
Shape t = new Triangle();
// set coordinates for a triangle
t.setCoordinates(new int[] {1,1, 2,2, 3,3});
// collect all shapes
Shape[] shapes = new Shape[] {r, t};
// arrange the for loop for all shapes in the array
for(int i=0; i < shapes.length; i++) {
// get the next shape
Shape shape = shapes[i]; // one of shapes, at run-time will be a specific shape: rectangle or triangle
// will draw a specific shape based on the nature of the object
shape.draw(); // will pick up a specific draw() method from a specific class Rectangle or Triangle
} // end of the loop
} // end of the main method
} // end of the class
Was it clear so far?
By the way a specific implementation of a method that is already provided and can be used for runtime polymorphism is called Method Overriding.
Yes, one more term to remember.
And please do not mix Method Overriding with Method Overloading.
What is Method Overloading?
A class can have multiple methods by same name but different parameters.
This is known as Method Overloading
Example:
public int sumNumbers(int a, int b) {
return a + b;
}
public double sumNumbers(double a, double b, double c) {
return a + b + c;
}
Here are the screen shots and illustrations related to the project.
Creating MoneyManagement interface
Testing Money Monegement family of implementation classes
Assignments: 1. Open Eclipse and create the package day5 in the project week1.
2. Under the package day5 type (do not copy/paste) the interface and implementations of MoneyManagement, including the TestMoneyManagement class and run this class.
3. Search Google and Youtube for the best presentations on this subject, read, watch, select and email 2 best links to dean@ituniversity.us
Answer the QnA and create at least 3 more high quality QnA related to the subject. Type all 3 of them into a text file 1.2.7.QnA.Your.Name.txt - prepared in WordPad (not MS Word!). Email this file to dean@ituniversity.us
Optional Reading recommended by students:
This link runs through the syntax of interfaces and abstract classes.
https://www.youtube.com/watch?v=1PPDoAKbaNA
Difference between abstract classes and interfaces
http://beginnersbook.com/2013/05/abstract-class-vs-interface-in-java/
This link goes into more in depth examples of using interfaces and abstract classes.
https://www.youtube.com/watch?v=AU07jJc_qMQ&ebc=ANyPxKq3jSqkNSWg9m8CuFWuSsoGdkSbislkELnfpdJP2cwitpeSGtHHVDQ3FSmbf9CDHq2q0vZiLnqER-bE1GH4vWu8-MLQRw
<br/>public interface MoneyManagement {
<br/>// just a signature: return type, the name of a method and possible arguments (in that case ? none)
<br/> public void manageMoney();
<br/> // there could be more method-signatures
<br/>}
<br/>
Here are the implementation classes defined in different files (remember that each class or interface must be defined in a separate file with the same name and extension .java):
<br/>public class MotherMoneyManagement implements MoneyManagement {
<br/> // implementation of the manageMoney method
<br/> public void manageMoney() {
<br/> System.out.println("Spend wisely and SAVE!");
<br/> }
<br/>}
<br/>public class DaughterMoneyManagement implements MoneyManagement {
<br/> // implementation of the manageMoney method
<br/> public void manageMoney() {
<br/> System.out.println("Do more shopping!");
<br/> }
<br/>}
<br/>
<br/>public class SonMoneyManagement implements MoneyManagement {
<br/> // implementation of the manageMoney method
<br/> public void manageMoney() {
<br/> System.out.println("Buy gifts for my girlfriend!");
<br/> }
<br/>}
<br/>
Three classes implement the same interface in a different way.
These three classes have a common interface that can be considered as a parent. So these three classes are actually from the same family, a family of MoneyManagement.
We can say for any object of any of these three classes that this is an object type of MoneyManagement.
Why would we want to generalize this way?
The benefit is their polymorphic behavior. Here is an example of polymorphism, where we deal with an array of the MoneyManagement objects, where each object has a specific type MotherMoneyManagement, DaughterMoneyManagement or SonMoneyManagement.
Example:
<br/>public class TestMoneyManagement {
<br/> public static void main(String[] args) {
<br/> MoneyManagement mmm = new MotherMoneyManagement();
<br/> MoneyManagement dmm = new DaughterMoneyManagement();
<br/> MoneyManagement smm = new SonMoneyManagement();
<br/> // collect these objects into an array of MoneyManagement[] objects
<br/> MoneyManagement[] familyMoneyManagement = new MoneyManagement[] {mmm, dmm, smm};
<br/> for(int i=0; i < familyMoneyManagement.length; i++) {
<br/> // get the next element of the array
<br/> MoneyManagement mm = familyMoneyManagement[i];
<br/> // invoke the manageMoney() method
<br/> mm.manageMoney(); // each time it will produce a different message
<br/> }
<br/> }
<br/>}
<br/>
Starting with Java 8, default and static methods may have implementation in the interface definition.
Interfaces can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
Interfaces as well as abstract classes cannot be instantiated. (See later about abstract classes.) You cannot create an object of an interface or an object of an abstract class. They both have not been defined completely. They are just templates.
Example: MoneyManagement mm = new MoneyManagement(); // will produce a compiler error
What is an abstract class?
Abstract class can have data and fully defined methods, but if at least one of the methods is not defined, does not have a body, this is an abstract class.
Example:
<br/>public abstract class Shape {
<br/> // data
<br/> private int[] coordinates; // x, y, z and maybe more coordinates to draw a shape
<br/> // methods
<br/> public int[] getCoordinates() {
<br/> return coordinates;
<br/> }
<br/> public void setCoordinates(int[] coordinates) {
<br/> this.coordinates = coordinates;
<br/> }
<br/> // method signature only, there is no body; this method makes the class abstract
<br/> public void draw(); // to be implemented in subclasses
<br/>}
<br/>
<br/>public class Rectangle extends Shape {
<br/> public void draw() {
<br/> // implementation: using coordinates to draw a rectangle
<br/> }
<br/>}
<br/>public class Triangle extends Shape {
<br/> public void draw() {
<br/> // implementation: using coordinates to draw a triangle
<br/> }
<br/>}
<br/>public class TestShapes {
<br/> public static void main(String[] args) {
<br/> Shape r = new Rectangle();
<br/> // set coordinates for a rectangle
<br/> r.setCoordinates(new int[] {1,1, 2,2, 3,3, 4,4});
<br/> Shape t = new Triangle();
<br/> // set coordinates for a triangle
<br/> t.setCoordinates(new int[] {1,1, 2,2, 3,3});
<br/> // collect all shapes
<br/> Shape[] shapes = new Shape[] {r, t};
<br/> // arrange the for loop for all shapes in the array
<br/> for(int i=0; i < shapes.length; i++) {
<br/> // get the next shape
<br/> Shape shape = shapes[i]; // one of shapes, at run-time will be a specific shape: rectangle or triangle
<br/> // will draw a specific shape based on the nature of the object
<br/> shape.draw(); // will pick up a specific draw() method from a specific class Rectangle or Triangle
<br/> } // end of the loop
<br/> } // end of the main method
<br/>} // end of the class
<br/>
Was it clear so far?
onclick="window.location.href='/BASE/jsp/demo.jsp?checkFlavor=itsp&issueID=19&intro=general&group=aitu&ur=f'">
By the way a specific implementation of a method that is already provided and can be used for runtime polymorphism is called Method Overriding.
Yes, one more term to remember.
And please do not mix Method Overriding with Method Overloading.
What is Method Overloading?
A class can have multiple methods by same name but different parameters.
This is known as Method Overloading
<br/>Example:
<br/>public int sumNumbers(int a, int b) {
<br/> return a + b;
<br/>}
<br/>
<br/>public double sumNumbers(double a, double b, double c) {
<br/> return a + b + c;
<br/>}
<br/>
Here are the screen shots and illustrations related to the project.
Creating MoneyManagement interface
Testing Money Monegement family of implementation classes
Assignments: 1. Open Eclipse and create the package day5 in the project week1.
2. Under the package day5 type (do not copy/paste) the interface and implementations of MoneyManagement, including the TestMoneyManagement class and run this class.
3. Search Google and Youtube for the best presentations on this subject, read, watch, select and email 2 best links to dean@ituniversity.us
Answer the QnA and create at least 3 more high quality QnA related to the subject. Type all 3 of them into a text file 1.2.7.QnA.Your.Name.txt - prepared in WordPad (not MS Word!). Email this file to dean@ituniversity.us
Optional Reading recommended by students:
This link runs through the syntax of interfaces and abstract classes.
https://www.youtube.com/watch?v=1PPDoAKbaNA
Difference between abstract classes and interfaces
http://beginnersbook.com/2013/05/abstract-class-vs-interface-in-java/
This link goes into more in depth examples of using interfaces and abstract classes.
https://www.youtube.com/watch?v=AU07jJc_qMQ&ebc=ANyPxKq3jSqkNSWg9m8CuFWuSsoGdkSbislkELnfpdJP2cwitpeSGtHHVDQ3FSmbf9CDHq2q0vZiLnqER-bE1GH4vWu8-MLQRw