Você está na página 1de 29

INHERITANCE

Inheritance

• Inheritance enables you to define a new class based on a


class that already exists.
• The new class will be similar to the existing class, but will
have some new characteristics.
• Java allows single inheritance (as opposed to multiple
inheritance)
Simple Single Inheritance

• The class that is used as a basis for defining a new


class is called a parent class (or superclass or
base class.)
• The new class based on the parent class is called a
child class (or subclass or derived class)
• The child class inherits the properties of the parent
class plus its own properties.
• The properties refer to the method(s) or the
attribute(s) (data)
• Inheritance is ‘is-a’ relationship
Is-a Relationship

• The picture shows a parent


class and a child class. The
line between them shows the
"is-a" relationship.
• We can say “Ford is an
Automobile”
• Inheritance is between
classes, not between objects.
Hierarchies

• In a hierarchy, each class has


at most one parent, but might
have several child classes.
• There is one class, at the "top"
of the hierarchy that has no
parent. This is sometimes
called the root of the hierarchy.
Inheritance – child class inherits parent class

Rectangle
• Super class – Rectangle
double length • Sub class – Cubes
double width • Attributes for Rectangle : length & width
• Attribute for Box : length, width & height

Box class inherits the length and


width of the Rectangle class
(superclass)
Box
double height
Syntax of Deriving a Child
Class
•The keyword to implement inheritance in Java is
extends .

public class childClass extends parentClass {

// new characteristics of the child class go here

•Examples:

public class Cat extends Animal {

public class HelloWorldActivity extends Activity {

}
Example: Rectangle class
public class Rectangle
{
private double length;
private double width;

public Rectangle(double L, double W) {


length = L;
width = W;
}

public double getLength() {


return length;
}

public double getWidth() {


return width;
}

public double area() {


return length * width;
}
}
Example: Box class
public class Box extends Rectangle
{
private double height;

public Box(double L, double W, double H) {


super(L,W);
height = H;
}

public double getHeight() {


return height;
}

@Override
public double area() {
return 2 * (getLength() * getWidth() + getLength() * height +
getWidth() * height);
}

public double volume() {


return super.area() * height;
}
}
Using a Super Class’s
Constructor
// constructor
public Box(double L, double W, double H) {
super(L,W); ); // use the super class'
constuctor
height = H; // initialize what's new to
Box
}
• The statement super( ) invokes the super class' constructor
to initialize some of the data. Then the next statements
initialize the members that only subclass has.
• When super is used in this way, it must be the first
statement in the subclass' constructor.
Overriding Methods

// added to class Box


@Override
public double area() {
return 2 * (getLength() * getWidth() + getLength() * height
+ getWidth() * height);
}

• A child overrides a method from its parent by defining a


replacement method with the same signature.
• The parent has its method, and the child has its own
method with the same name.
Using super in Child’s
Methods

public double volume() {


return super.area() * height;
}

• The statement super.method() invokes the super class'


method() that has been overridden by the subclass.
• Unlike the case when super is used in a constructor, inside
a method super does not have to be used in the first
statement.
Superclass’s Constructor Is Always Invoked
A subclass constructor may invoke its superclass’s
constructor. If none is invoked explicitly, the compiler
puts super() as the first statement in the constructor.
For example, the constructor of class A:

public A() { public A() {


is equivalent to
}  super();

 
 

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
}  // some statements
  } 
 
Example on the Impact of a Superclass without no-arg
Constructor

Find out the error in the program:

class Fruit {
public Fruit(String name) {
System.out.println("Fruit constructor is invoked");
}
}

public class Apple extends Fruit {


public Apple(String name) {
System.out.println(“Apple constructor is invoked");
}
}
Accessibility Modifier

• Sometimes , it is called visibility modifier


• Not all properties can be accessed by subclass.
• Super class can control access to its member from its subclass
by giving the type of accessing to its members.
• A class can declare its data or methods as public, private or
protected.
• If it is not declared, the data or method will be set to default type.
Accessibility Modifier
Example: Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }

package p2;

public class C3 public class C4 public class C5 {


extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }
Polymorphism

• Polymorphism means "having many forms“ – can refer to multiple


types of related objects over time in consistence way.
• Polymorphism is one of the most elegant uses of inheritance.
• A polymorphic reference is a variable that can refer to different
types of objects at different points in time. Specifically, a reference
variable of a superclass type can refer to any object of its
subclasses in the inheritance hierarchy.
Polymorphic
Reference
• For example, if the Animal class is the parent class for Cat &
Dog class, then an Animal reference variable can be used to
refer to a Cat & Dog object
• Similarly, Animal can refer to any of its child classes

Animal Animal myPet;


myPet = new Cat();
myPet = new Dog();
Dog Cat
Polymorphic Behaviour

• When a method is invoked using the superclass variable, it is


the class of the object (not of the variable type) that
determines which method is run.

Animal myPet = new Animal();


myPet.sound(); //invokes Animal sound

myPet = new Cat();


myPet.sound(); //invokes Cat sound

myPet = new Dog();


myPet.sound(); //invokes Dog sound
Polymorphic Behaviour

• 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():

Animal myPet = new Cat();


myPet.purr(); //======== error!!
The instanceof Operator
• The instanceof keyword can test if an object is of a specific type (an
instance of a specific class)
• The instanceof is a Boolean operator generate a true or a false result)
• The following code test whether an Animal is a Cat or a Dog

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)

if(pet instanceof Cat)


{
// pet.purr(); ======== error!!
Cat myPet = (Cat) pet;
myPet.purr(); // now ok!
}
Abstract class

• An abstract class is a class that cannot be instantiated but can be the


parent of other classes.
• Objects can ONLY be created from child class that inherits from the
abstract parent class
• It is declared with the reserved word abstract in its heading.

abstract class ClassName {


// definitions of methods and variables
}
Abstract Method

• An abstract class can contain abstract method(s).

• If a class contains an abstract method, then the class must be


declared abstract.

• We cannot instantiate an object from abstract class. We can only


declare a reference variable of an abstract class type.

• We can instantiate an object of a child class of an abstract class,


but the child class must override all of the abstract methods of
the parent class.
Abstract Method

• 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.

public abstract void print();


public abstract String larger(int value);
void abstract insert(Object item);
Example of an abstract class & method

public abstract class Animal


{
protected String type;
public Animal(String t)
{ type = t;
}
public abstract void sound();
}
Interface

• An interface is similar to abstract class but all of its methods


MUST be abstract
• Interface can be used to organize object behaviours by defining
some behaviours(methods) that can be applied to an object.
• For example, we could define a Swimmer interface that provides
a set of methods that are common across all objects that can
swim

public interface Swimmer {


void startSwimming(); //no need to specify abstract keyword
void stopSwimming();
void dive();
void surface();
}
Interface

• 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
}
}

Você também pode gostar