The three important
concepts in Objected Oriented Programming are:
1. Data Abstraction
Encapsulation (classes)
and Information hiding (private access)
Interfaces are useful for Data Abstraction.
They provide methods without implementation. An Interface variable can be
assigned any of its implementation variables. An Interface variable can be cast
to any of its implementations. Any class variable can be cast to an Interface.
2. Inheritance and Interfaces
A class can extend another class. This means that
all of the variables and methods from the first (super or base) class are
automatically members of the new (extended) class. New variables and/or methods
can be added to the extended class and methods from the super class can be overridden
in the extended class. A method from the super class is overridden in the
extended class if it has the same signature. The inheritance syntax in Java is [public]
class ExtendedClass extends SuperClass
{...}.
A SuperClass
variable can be assigned any ExtendedClass value.
The reverse is not true i.e. an ExtendedClass
variable cannot be assigned a SuperClass value. A
SuperClass variable can be cast to any of it's extended classes.
3. Polymorphism
A polymorphic variable
is one that can be assigned values of different types. When this variable
accesses a method that has the same signature for the different types the
binding of the method is done at run time (dynamic binding). The method that is
used is the one that corresponds to the current value of the variable. This is
achieved in Java by overriding class methods in extended classes.
The keyword super
refers to the super class and this refers to the "current" object. As
noted above a super class variable can be assigned a subclass value. This means
a super class variable can reference a subclass object. If the super class
variable accesses an overridden method then method chosen is from the object
being referenced, not from the type of the reference variable. So:
class
SubClass extends SuperClass
{...}
SuperClass
S;
SubClass
T = new SubClass();
T = S; // this is
NOT OK
S = new SubClass(...);//
this is OK
S.superMethod(); // is OK
S.subMethod(); // is NOT
OK unless overridden
S.subOverriddenMethod(); // is
OK and chooses the SubClass version
((SubClass)S).subMethod(); // is OK. If S
did not contain a SubClass value then an CastClassException will be
thrown
All classes in Java
implicitly extend a class named Object. This means that any class value can be
assigned to an Object variable and an Object variable can be cast to any class
and the compiler will not object. A CastClassException
could still be thrown at run time.