You are on page 1of 23

Day 1 – Singleton Pattern

 A typical class contains 2 things: interface and


implementation.
 Interface is a list of executable method (public
method).
 An Implementation is a logic within a method.
 Java treats interface and implementation as two
separate entities.
Interface of Class A contains 1 method
only – Class A {
public int compute().
public int compute() {
return 1 + 1;
}
private void doSomething() {
System.out.println(“do
Implementation
something.”);
}
}
INTERFACE CLASS
Lion lion = new Lion();

Interface Actual Instance (Implementation)

Animal lion = new Lion();

This is valid! Provided Lion uses Animal Interface


 Invoking a method involves 2 steps:
 1. Find the method in the interface.
 2. if the method found, Execute it. Otherwise, flag
error.
INTERFACE CLASS THAT IMPLEMENTS INTERFACE
CORRECT WRONG

Lion lion = new Lion(); Animal lion = new Lion();


lion.run(); lion.roar();
lion.roar();

Animal lion = new Lion();


lion.run();
Lion lion = null;
lion.roar();
 Create 1 interface, with at least one method.
 Create 2 classes which implements the interface
created in step 1.
 Use ArrayList to store instances of the 2 classes.
 For every instance in ArrayList, simply call one
method.
INHERITANCE & INTERFACE REFERENCE

SuperClass Interface

+getSize() +getSize() ClassA


ClassB
+classB

SubClass Class
Human Money
+money
ISuperHero

+fly()

Superman Hand
+hand

Please write code for the above UML diagram.


It should have 3 classes.
 Ensure only one instance exist!
 Example usage: Data Source. Calendar.
CODE RESULT
CODE RESULT
 When we are creating an
instance, we will invoke the
constructor automatically.
 Human h1 = new Human();
 Human h2 = new Human();
 If we set the constructor as
private, we will fail to create
the instance.
 The only way to call the
private constructor is by
calling it from the class itself!
CONVERT THIS ONE! CLIENT PROGRAM

You might also like