Interfaces & Abstract Classes
Interfaces
an interface is a class that only has
method headers; if you use (implement) an interface, you must
provide a body for every method in the header
Example of using an interface:
//here is the
interface
//only method headers -- no bodies
//for the methods..
public interface Info
{
public int tryIt(int i);
public void hiThere();
}
//here is the
class which uses (implements the
//interface called Info) must provide a body for
//all methods in the interface called Info
//The class called NewInfo which implements
//the interface Info can have its own methods as well
public class NewInfo
implements Info {
private int type;
//from interface
public int tryIt(int i) {
int x;
x = i * 5;
return x;
}
//from
interface
public void hiThere() {
System.out.println("hi there!");
}
//regular
method in NewInfo
public void doThat(int i) {
int i= 5 * 9;
}
}
Abstract Classes
used with inheritance
a normal class with the exception that
their is at least one method in the abstract class that only
contains a method header (a method without a body). If you use the
abstract class as a parent, you must provide
a body for all method headers in the
parent abstract class.
In essence, a abstract class is a
combination of both a normal class and a interface. It is a
placeholder in a system.
//here is the
abstract class
//both method headers and methods with a body
public class Info {
private int theOne;
public int tryIt(int i); //an abstract method -
no body
public void hiThere() {
System.out.println("hi there!"); }
}
}
//here is the
child class
//method headers must be written with a body
//for all abstract class from parent
public class BabyInfo extends Info {
//an abstract method - provide a body for
public int tryIt(int i) {
int x = i +
7;
return (x);
}
public void noNo() {
System.out.println("No No!"); }
}
}
|