abstract class and interface
DESCRIPTION
Understanding: - Abstract class - Interface - DifferencesTRANSCRIPT
Abstract class and Interface
Group 3, Kompongsom Class
Member
• Leang Bunrong• Heak Menghok• Chea Socheat• Choun Sreynav• Buoy Sodeth
Content
• Abstract Class• Interface• Abstract class vs. Interface
Abstract Class
• Declared with abstract keyword• May or may not include abstract methods• Abstract class’s method can be public,
protected or default• Can not be instantiated• Can also be subclass• Non-abstract subclass must implement all
abstract methods of superclass
Abstract Class (cont.)
When use Abstract class?• Used to shared code to Related classes• When subclasses have many common
methods or fields• Provide default behavior (method)
Abstract Class (cont.)abstract class Animal {
public void eat(Food food) { /*Body statement*/ }public void sleep(int hours) {/*Body statement*/ }public abstract void makeNoise();
}
class Dog extends Animal{@Overridevoid makeNoise(){
System.out.println(“woof”);}
}
class Cat extends Animal{@Overridevoid makeNoise(){
System.out.println(“meow”);}
}
Interface
• Contains only Constants, method signatures• All fields in Interface are public, static and final• All methods in Interface are public and abstract• Can not be instantiated• Allow multiple implementations• Used when unrelated class using same name of
methods• Multi inheritance
Interface (cont.)interface IAnimal{
void walk();}
class Cat implements IAnimal{@Overridevoid walk(){
System.out.println(“Cat’s walking”);}
}
Differences
Abstract Class• Contains abstract/non-abstract
methods• Method can be public, protected,
default, private*• All field can be public, protected,
default, private, static or final• Single inheritance• Used when subclasses have many
common field/methods• Can be subclass
* non-abstract method only
Interface• Contains abstract methods
• Methods have to be public
• All fields are public static and final
• Multiple implementations• Used when classes using same
name of methods
Thank for paying Attention.
Questions?