Inheritance & Polymorphism

16
Eng. Mohammed S. Abdualal Inheritance & Polymorphism February 21, 2015 Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2124) ______________________________________________________________ Lab 1 Inheritance & Polymorphism Eng. Mohammed S. Abdualal

Transcript of Inheritance & Polymorphism

Page 1: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Islamic University of Gaza

Faculty of Engineering

Computer Engineering Department

Computer Programming Lab (ECOM 2124)

______________________________________________________________

Lab 1

Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Page 2: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Inheritance

Inheritance can be defined as the process where one object acquires the

properties of another. With the use of inheritance, the information is made

manageable in a hierarchical order. When we talk about inheritance, the most

commonly used keyword would be extends and implements. These words would

determine whether one object IS-A type of another. By using these

keywords we can make one object acquire the properties of another object.

IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how the

extends keyword is used to achieve inheritance.

public class Animal{

}

public class Mammal extends Animal{

}

public class Reptile extends Animal{

}

public class Dog extends Mammal{

}

Now, based on the above example, In Object Oriented terms the following are

true:

Animal is the superclass of Mammal class.

Animal is the superclass of Reptile class.

Mammal and Reptile are subclasses of Animal class.

Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say:

Mammal IS-A Animal

Reptile IS-A Animal

Dog IS-A Mammal

Hence : Dog IS-A Animal as well

*Important :With use of the extends keyword the subclasses will be able to

inherit all the properties of the superclass except for the private properties of

the superclass. We can assure that Mammal is actually an Animal with the use of

the instance operator.

Page 3: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

The instanceof Keyword:

Example:

public class Dog extends Mammal{

public static void main(String args[]){

Animal a =new Animal();

Mammal m =new Mammal();

Dog d =new Dog();

System.out.println(m instanceof Animal);

System.out.println(d instanceof Mammal);

System.out.println(d instanceof Animal);

}

}

Result:?

Since we have a good understanding of the extends keyword, let us look into

how the implements keyword is used to get the IS-A relationship.

The implements keyword is used by classes by inherit from interfaces.

Interfaces can never be extended by the classes.

Example :

public interface Animal{

}

public class Mammal implements Animal{

}

public class Dog extends Mammal{

}

Let us use the instanceof operator to check determine whether Mammal is

actually an Animal, and dog is actually an Animal

interface Animal{

}

class Mammal implements Animal{

}

public class Dog extends Mammal{

public static void main(String args[]){

Mammal m =new Mammal();

Dog d =new Dog();

System.out.println(m instanceof Animal);

System.out.println(d instanceof Mammal);

System.out.println(d instanceof Animal);

}

}

Page 4: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Result ?

HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a

certain class HAS-Acertain thing. This relationship helps to reduce duplication of code as well as bugs.

Lets us look into an example:

public class Vehicle{

}

public class Speed{

}

public class Van extends Vehicle{

private Speed sp;

}

This shows that class Van HAS-A Speed. By having a separate class for Speed,

we do not have to put the entire code that belongs to speed inside the Van class

which makes it possible to reuse the Speed class in multiple applications

*A very important fact to remember is that Java only supports only single

inheritance. This means that a class cannot extend more than one class.

Therefore following is illegal:

public class extends Animal,Mammal{

}

However, a class can implement one or more interfaces. This has made Java get

rid of the impossibility of multiple inheritance.

It's very important to know this:

Contrary to the conventional interpretation, a subclass is not a subset

of its superclass. In fact, a subclass usually contains more information

and methods than its superclass.

Private data fields in a superclass are not accessible outside the

class. Therefore, they cannot be used directly in a subclass. They can,

however, be accessed/mutated through public accessors/mutators

(getter, setter) if defined in the superclass.

Page 5: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Using the super Keyword :

The keyword super refers to the superclass and can be used to invoke the superclass's methods and constructors.

Think

A subclass inherits accessible data fields and methods from its superclass. Does

it inherit constructors? Can the superclass’s constructors be invoked from a

subclass?

The this Reference, introduced the use of the keyword this to reference

the calling object.

The keyword super refers to the superclass of the class in which super appears.

It can be used in two ways:

To call a superclass constructor.

To call a superclass method.

A constructor is used to construct an instance of a class. Unlike properties and

methods, the constructors of a superclass are not inherited by a subclass.

They can only be invoked from the constructors of the subclasses using the

keyword super.

The syntax to call a superclass’s constructor is:

super(); or super(parameters);

*The statement super() invokes the no-arg constructor of its superclass, and

the statement super(arguments) invokes the superclass constructor that

matches the arguments.

*The statement super() or super(arguments) must be the first statement of the

subclass’s constructor;

Page 6: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

public class Faculty extends Employee {

public static void main(String[] args) {

new Faculty();

}

public Faculty() {

System.out.println("(4) Performs Faculty's tasks");

}

}

class Employee extends Person {

public Employee() {

this("(2) Invoke Employee's overloaded constructor");

System.out.println("(3) Performs Employee's tasks ");

}

public Employee(String s) {

System.out.println(s);

}

}

class Person {

public Person() {

System.out.println("(1) Performs Person's tasks");

}

}

Question :

What's a problem in this code below ?

class Apple extends Fruit {

}

class Fruit {

public Fruit(String name) {

System.out.println("Fruit's constructor is invoked");

}

}

Page 7: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

The keyword super can also be used to reference a method other than the

constructor in the

superclass. The syntax is:

super.method(parameters);

Example :

public void printCircle() {

System.out.println("The circle is created " +

super.getDateCreated() + " and the radius is " + radius);

}

Question :

1. What is the output of running the class C in (a)? What problem arises in

compiling the program in (b) (2 solutions)?

class A {

public A() {

System.out.println(

"A's no-arg constructor is invoked");

}

}

class B extends A {

public B(){

System.out.println("B'sno-arg constructor is invoked");

}

}

class C {

public static void main(String[] args) {

B b = new B();

}

}

(a)

Page 8: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

2. How does a subclass invoke its superclass’s constructor?

3. True or false? When invoking a constructor from a subclass, its

superclass’s no-arg constructor is always invoked.

Overriding Methods

To override a method, the method must be defined in the subclass using the same signature and the same return type as in its superclass.

Benefit from override : A subclass inherits methods from a superclass.

Sometimes it is necessary for the subclass to modify the implementation of a

method defined in the superclass.

Important things :

*override the method provided that it is not marked final.

*An instance method can be overridden only if it is accessible. Thus a private

method cannot be overridden, because it is not accessible outside its own class.

If a method defined in a subclass is private in its superclass, the two methods

are completely unrelated.

*a static method can be inherited. However, a static method cannot be

overridden. If a static method defined in the superclass is redefined in a

subclass, the method defined in the superclass is hidden. The hidden static

methods can be invoked using the syntax SuperClassName.staticMethodName.

class A {

public A(int x) {

System.out.println(

"A's no-arg constructor is invoked");

}

}

class B extends A {

}

class C {

public static void main(String[] args) {

B b = new B();

}

} (b)

Page 9: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Example:

class Animal {

public void move() {

System.out.println("Animals can move");

}

}

class Dog extends Animal {

public void move() {

System.out.println("Dogs can walk and run");

}

}

class TestDog {

public static void main(String args[]) {

Animal a = new Animal();// Animal reference and object

Animal b = new Dog();// Animal reference but Dog object

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class

}

}

Result ?

Example: Can anyone explain what’s the meaning from red line ?

Hint : you have to understand the output of the code to answer the question

class Animal {

public void move() {

System.out.println("Animals can move");

}

public void stop() {

System.out.println("Animals can stop");

}

}

class Dog extends Animal {

public void move() {

System.out.println("Dogs can walk and run");

}

}

class TestDog {

public static void main(String args[]) {

Animal a = new Animal();// Animal reference and object

Animal b = new Dog();// Animal reference but Dog object

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class

b.stop();//Runs the method in Animal class

a.stop();//Runs the method in Animal class

}

Page 10: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Question

True or false? You can override a private method defined in a superclass.

True or false? You can override a static method defined in a superclass.

How do you explicitly invoke a superclass’s constructor from a subclass?

How do you invoke an overridden superclass method from a subclass?

Overloading means to define multiple methods with the same name but different signatures. Overriding means to provide a new implementation for a method in the subclass.

class Test {

public static void main(String[] args)

{

A a = new A();

a.p(10);

a.p(10.0);

}

}

class B {

public void p(double i) {

System.out.println(i * 2);

}

}

class A extends B {

// This method overrides the method in B

public void p(double i) {

System.out.println(i);

}

}

class Test {

public static void main(String[] args) {

A a = new A();

a.p(10);

a.p(10.0);

}

}

class B {

public void p(double i) {

System.out.println(i * 2);

}

}

class A extends B {

// This method overloads the method in B

public void p(int i) {

System.out.println(i);

}

}

Page 11: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Question :

Identify the problems in the following code:

Important to know

If no inheritance is specified when a class is defined,

the superclass of the class is Object by default.

class Circle {

private double radius;

public Circle(double radius) {

radius = radius;

}

public double getRadius() {

return radius;

}

public double getArea() {

return radius * radius * Math.PI;

}

}

class B extends Circle {

private double length;

B(double radius, double length) {

super(radius);

length = length;

}

@Override

public double getArea() {

return getArea() * length;

}

}

Page 12: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Polymorphism

Polymorphism is the ability of an object to take on many forms.

A parent class reference is used to refer to a child class object.

Any Java object that can pass more than one IS-A test is considered to

be polymorphic.

Example

Let us look at an example.

public interface Vegetarian{}

public class Animal{}

public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple

inheritance. Following are true for the above example:

A Deer IS-A Animal

A Deer IS-A Vegetarian

A Deer IS-A Deer

A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the

following declarations are legal:

Deer d = new Deer();

Animal a = d;

Vegetarian v = d;

Object o = d;

*Note: All the reference variables d,a,v,o refer to the same Deer object in the

heap.

Page 13: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Virtual Methods

A child class can override a method in its parent. An overridden method is

essentially hidden in the parent class, and is not invoked unless the child class

uses the super keyword within the overriding method.

class Test {

public static void main(String[] args) {

Salary s = new Salary("Mohammed Abdual Al", "Gaza,Al-Remal", 3, 3600.00);

Employee e = new Salary("Muhammad O Shehada", "USA,:)", 2, 2400.00);

System.out.println("Call mailCheck using Salary reference --");

s.mailCheck();

System.out.println("\n Call mailCheck using Employee reference--");

e.mailCheck();

}

}

class Employee

{

private String name;

private String address;

private int number;

public Employee(String name, String address, int number)

{

System.out.println("Constructing an Employee");

this.name = name;

this.address = address;

this.number = number;

}

public void mailCheck()

{

System.out.println("Mailing a check to " + this.name

+ " " + this.address);

}

public String toString()

{

return name + " " + address + " " + number;

}

public String getName()

{

return name;

}

public String getAddress()

{

return address;

}

public void setAddress(String newAddress)

{

address = newAddress;

}

public int getNumber()

{

return number;

}

}

Page 14: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

class Salary extends Employee

{

private double salary; //Annual salary

public Salary(String name, String address, int number, double

salary)

{

super(name, address, number);

setSalary(salary);

}

public void mailCheck()

{

System.out.println("Within mailCheck of Salary class ");

System.out.println("Mailing check to " + getName()

+ " with salary " + salary);

}

public double getSalary()

{

return salary;

}

public void setSalary(double newSalary)

{

if(newSalary >= 0.0)

{

salary = newSalary;

}

}

public double computePay()

{

System.out.println("Computing salary pay for " + getName());

return salary/52;

}

}

Page 15: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

The protected Data and Methods

A protected member of a class can be accessed from a subclass.

Page 16: Inheritance & Polymorphism

Eng. Mohammed S. Abdualal

Inheritance & Polymorphism

February 21, 2015

Homework

Problem: (The Person, Student, Employee, Faculty, and Staff classes) Design a class named Person and its two subclasses named Student and Employee. Make Faculty and Staff subclasses of Employee. A person has a name, address, phone number, and email address. A student has a class status (freshman, sophomore, junior, or senior). Define the status as a constant. An employee has an office, salary, date hired. Define a class named MyDate that contains the fields year, month, and day. A faculty member has office hours and a rank. A staff member has a title. Overridden the toString method in each class to display the class name and the person's name. Implement the classes. Write a test program that creates a Person, Student, Employee, Faculty, and Staff, and invokes their toString() methods.