Lecture 4 - Interfaces
Lecture 4 - Interfaces
Abstract Classes
Interfaces
Inner Classes
Abstract Classes
An abstract class is a class that is declared abstract
Abstract classes can not be instantiated, but can be sub - classed
Abstract classes are used only as super classes in inheritance hierarchies
Abstract class are used to share a common design
Abstract Classes
public abstract class Animal {
//declare fields
//declare non - abstract methods
public abstract void makeNoise();
}
When an abstract class is sub-classed, all of the abstract methods in its parent class
must be implemented (concrete class)
However, if it does not, then the subclass must also be declared abstract
Abstract Methods
An abstract method is a method that is declared without an
implementation
abstract void moveTo( double x, double y);
Abstract method is followed by a semicolon but no braces
Is there something more abstract?
void setTime (int hour, int minute, int second); Abstract method
void setDate (int day, int month, int year);
}
The Interface Body
All abstract and static methods are implicitly public
All constant values are implicitly public, static and final
Implementing an Interface
implements keyword is used to declare a class that implements in
interface
A class can implement more than one interface
Interfaces implemented by the class are specified after implements keyword as
a comma - separated list
Flying Horse
Multiple Inheritance
public class Horse { pubic class Eagle {
int noOfLegs = 4; int noOfLegs = 2;
public void makeNoise () { public void makeNoise () {
System.out.printlin (“Neigh”); System.out.pintln (“Eagle Sound”);
} }
} public void fly() {}
}
public class Hippogriff extends Horse, Eagle{
int noOfLegs - > 2 or 4 ???
public void makeNoise() {} - > “Neigh” or “Eagle Sound ” ???
}
Multiple Inheritance by Type
public class Horse { Public interface Flyable {
int noOfLegs = 4; public void fly();
public void makeNoise () { }
System.out.printlin (“Neigh”);
}
}
public class Hippogriff extends Horse implements Flyable {
public void fly() {
System.out.println (“Hippogriff Flying”);
}
}
Abstract Class vs. Interface
Can share common fields and methods Can share interface among several unrelated
among several closely related classes classes
Inner Class
A class within a class or method.
Normally a class cannot be private. However, you can make inner classes private.
-> Can be used as a security mechanism
public class OuterClass { public class MainClass {
private class InnerClass { public static void main(String args[]) {
public void someFuction() {…….} class AntotherInnerClass {…….}
AnotherInnerClass aIC = new AnotherInnerClass();
}
innerCls.someFunction(); }
} }
}
A real-world example of Inner Class
If you have Questions/Suggestions,
please bring them up in the forums!
Thank You