Escolar Documentos
Profissional Documentos
Cultura Documentos
Inheritance
Rectangle
• Super class – Rectangle
double length • Sub class – Cubes
double width • Attributes for Rectangle : length & width
• Attribute for Box : length, width & height
•Examples:
}
Example: Rectangle class
public class Rectangle
{
private double length;
private double width;
@Override
public double area() {
return 2 * (getLength() * getWidth() + getLength() * height +
getWidth() * height);
}
class Fruit {
public Fruit(String name) {
System.out.println("Fruit constructor is invoked");
}
}
package p2;
• The superclass type variable can only be used to invoke methods in subclass
that also exist in the superclass (overridden by subclass).
• New methods in subclass is not visible to the superclass variable .
• e.g. If Cat has a method purr():
void
void register(Animal
register(Animal pet)
pet)
{{
if(pet
if(pet instanceof
instanceof Cat)
Cat)
{{
//
// Registering
Registering aa Cat
Cat
}} else
else if(pet
if(pet instanceof
instanceof Dog)
Dog)
//
// Registering
Registering aa Dog
Dog
}} else
else {{
//
// Registering
Registering other
other animals
animals
}}
}}
Object Casting
• Once the type of object is identified (using instanceOf), the child object
referred by the parent reference variable can be cast to its type
• Use the cast operator : (ClassType)
• e.g. (pet is Animal type)
• An abstract method is a method that has only the header without body.
• The header of an abstract method must contain the reserved word
abstract and ends with semicolon(;).
• Syntax:
<AccessSpecifier> abstract ReturnType MethodName(ParameterList);
• E.g.
• A class like Dog (but not Cat!) could then implement the Swimmer
interface (using the implements keyword) and provide
implementations of the swimming behaviour (by overriding all the
abstract methods) :
public class Dog extends Animal implements Swimmer {
public void startSwimming() {
// Provide implementations of the startSwimming behaviour
}
void stopSwimming() {
// Provide implementations of the stopSwimming behaviour
}
void dive() {
// Provide implementations of the dive behaviour
}
void surface() {
// Provide implementations of the surface behaviour
}
}