CPE207 Object Oriented Programming (Week 10)
CPE207 Object Oriented Programming (Week 10)
Interfaces:
Abstraction, Multiple inheritance
2
Week 10
o.meow(); //??
((Animal)o).eat(); //??
((Animal)o).meow(); //??
((Cat)o).eat(); //?? (*)
((Cat)o).meow(); //??
4
There are mainly three reasons to use
interface. Using interface we can:
1. achieve abstraction.
2. support the functionality of multiple
inheritance.
3. achieve loose coupling.
2/10/2023 5
We already know
this!
6
An interface is created with the following syntax:
modifier interface InterfaceID {
//constants
//abstract method
}
An interface can extend other interfaces with the following syntax:
modifier interface interfaceID extends interface1, .., interfaceN {
//constants
//abstract method, (After Java 8.0 static and default methods)
}
7
1. Interfaces are like abstract classes.
2. An interface is not extended by a class; it is implemented by a
class. But, one interface can extend another one.
3. An interface does not contain any constructors.
4. A class can implement any number of interfaces.
(multiple inheritance)
5. Interfaces cannot be instantiated. (like abstract classes)
6. You can use interface as a data type for variables. (Like classes)
7. Interfaces can contain only abstract methods and constants.
8
Interface Abstract class
Variable Only constants Constants and variable
(attribute) data
12
Salary<<interface>> 1
CalculateSalary() declaration
Employee<<abstract>>
CalculateSalary() declaration
name; Employee<<abstract>>
wage;
name;
wage;
FullTimeEmployee PartTimeEmployee
FullTimeEmployee PartTimeEmployee
CalculateSalary() CalculateSalary()
CalculateSalary() hours; CalculateSalary() hours;
14
Print(); ColoredPrint(); Fax(); Scan();
Printer
}
}
The Hat is "loosely coupled" to the body. if you want to change the skin,
◦ This means you can easily take the hat off you would also HAVE TO change
without making any changes to the the design of your body as well
person/body. because the two are joined -
◦ When you can do that then you have "loose they are “tightly coupled”
coupling".
In short, loosely coupling makes code easier
to change.
18
Loose coupling is simply writing software in such a way that all
your classes can work independently without relying on each
other. MVC is a loosely coupled
19
Lab exercise