Computer Sciences 313e
- Inheritance
- To create a subclass, we use the extends keyword
- Subclasses inherit the variables and methods of the
parent class, and use them as if they were declared in the subclass.
Example:
class Animal
{
float weight;
int numberOfLegs;
void eat() {...}
void drink() {...}
void move() {...}
}
class Dog extends Animal
{
String breed;
// inherits weight, numberOfLegs
void bark() {...}
// inherits eat(), drink(), move()
}
Dog instances can be used anywhere Animal instances can be used.
Example:
Animal tbone;
tbone = new Dog();
tbone.move(); <--- A Dog instance is also an instance of Animal, so
the move() method can be invoked
Overriding
Methods in the Parent Class
- A subclass can redefine a method that it inherited from
its superclass.
- The subclass method overrides the superclass method,
and essentially replaces its implementation for instances of the
subclass.<>
Example
Overriding the move() method from Animal in the Dog class:
class Dog extends Animal
{
String breed;
// inherits weight, numberOfLegs
void bark() {...}
void move() { // a special version of the move()
method just for Dog objects }
// inherits eat(), drink()
}
Keyword
Super
- Super refers to members of the superclass.
- Common use: an overriding method in the subclass will
call the superclass method by the same name.
Example
class Dog extends Animal
{
String breed;
...
void move()
{
...
super.move(); // Call
implementation of move() in superclass Animal
}
}
- The statement super() calls the superclass constructor.
Example
class Person
{
Person(String name)
{ ... }
}
class Doctor extends Person
{
Doctor(String name, String specialization)
{
super(name); // Call the
Person constructor and pass in name
... // do some other stuff
}
}
- Using super in this way avoids code duplication and
thus makes our program easier to read.
- Since the Person class does not contain a default no
argument constructor, we must call super() explicitly. Otherwise the
compiler will complain that it cannot find a default constructor in the
parent class.