chapter3 inheritance

40
Object Oriented Programming Chapter 3: Inheritance Prepared by: Mahmoud Rafeek Alfarra 2016

Upload: mahmoud-alfarra

Post on 12-Apr-2017

321 views

Category:

Education


0 download

TRANSCRIPT

Object Oriented Programming

Chapter 3: Inheritance

Prepared by: Mahmoud Rafeek Alfarra

2016

قال الله تعالى:ذين0 أس0رفوا )قل0 ي0ا عبادي0 الهم ال تقنطوا م0ن عل0ى أنفس0ه00 يغفر ه00 إن00 الل حمة00 الل ره0 هو الغفور الذنوب0 جميع0ا إن

حيم( الر

Outlines◉Motivation

◉What is Inheritance ?

◉Types of Inheritance

◉Superclasses and Subclasses

◉Defining a Subclass

◉"is-a" and the "has-a" relationship

Note: I have prepared this material Based on )Liang: “Introduction to Programming using Java”, 10’th edition, 2015(

◉Are superclass’s Constructor Inherited?

◉Overriding Methods in the Subclass

◉Full Example

◉Important Notes

Lecture Let’s think on Inheritance

1

o Suppose you will define classes to model circles, rectangles, and triangles.

o These classes have many common features. What is the best way to design these classes so to avoid redundancy?

The answer is to use inheritance.

Motivation

What is Inheritance ?

o Inheritance is a form of software reuse in which a new class is created by absorbing an existing class's members and embellishing them with new or modified capabilities.P_Properties

P_ methods

Parent Class

C_Properties C_methods

Child Class This class has its properties, methods and that of its parent.

Types of Inheritance Single Inheritance

When a Derived Class to inherit properties and behavior from a single Base Class, it is called as single inheritance.

Multi Level Inheritance

A derived class is created from another derived class is called Multi Level Inheritance.

Hierarchical Inheritance

More than one derived class are created from a single base class, is called Hierarchical Inheritance

Types of Inheritance Hybrid Inheritance

Any combination of above three inheritance )single, hierarchical and multi level( is called as hybrid inheritance.

Multiple Inheritance

Multiple inheritances allows programmers to create classes that combine aspects of multiple classes and their corresponding hierarchies.

Superclasses and Subclasses

GeometricObject -color: String -filled: boolean -dateCreated: java.util.Date

+GeometricObject() +GeometricObject(color: String,

filled: boolean) +getColor(): String +setColor(color: String): void +isFilled(): boolean +setFilled(filled: boolean): void +getDateCreated(): java.util.Date +toString(): String

The color of the object (default: white). Indicates whether the object is filled with a color (default: false). The date when the object was created.

Creates a GeometricObject. Creates a GeometricObject with the specified color and filled

values. Returns the color. Sets a new color. Returns the filled property. Sets a new filled property. Returns the dateCreated. Returns a string representation of this object.

Circle -radius: double

+Circle() +Circle(radius: double) +Circle(radius: double, color: String,

filled: boolean) +getRadius(): double +setRadius(radius: double): void +getArea(): double +getPerimeter(): double +getDiameter(): double +printCircle(): void

Rectangle -width: double -height: double

+Rectangle() +Rectangle(width: double, height: double) +Rectangle(width: double, height: double

color: String, filled: boolean) +getWidth(): double +setWidth(width: double): void +getHeight(): double +setHeight(height: double): void +getArea(): double +getPerimeter(): double

o In Java, as in other object-oriented programming languages, classes can be derived from other classes.

o The derived class )the class that is derived from another class( is called a subclass.

o The class from which its derived is called the superclass.

Superclasses and Subclasses

o A subclass normally adds its own fields and methods.o Therefore, a subclass is more specific than its superclass.o Typically, the subclass exhibits the behaviors of its

superclass and additional behaviors that are specific to the subclass.

Superclasses and Subclasses

Direct & Indirect Superclasses

properties3 methods3 SubClass

properties1 methods1

IndirectSuperClass

properties2 methods2 Direct

SuperClass

o The direct superclass is the superclass from which the subclass explicitly inherits.

o An indirect superclass is any class above the direct superclass in the class hierarchy.

o A subclass inherits from a superclass. You can also: Add new properties Add new methods Override the methods of the superclass.

Defining a Subclass

Defining a Subclass

public class Faculty extends Employee {

//… }

SubClass SuperClass

Defining a Subclassclass Vehicle {

protected String model;protected float price;

public Vehicle(String model, float price){this.model = model;this.price = price;

}

public String print(){return "Model: "+model+"\t Price: "+price;

}

public void setModel(String model){this.model = model;}public String getModel(){

return model;} // set and get of price

}

Vehicle Class SuperClass

Car Class SubClass

Defining a Subclass

class Car extends Vehicle{private int passengers;

public Car(String model, float price,int passengers){super( model, price);this.passengers = passengers;

}

public String print(){return "Data is:\n"+super.print()+

" # of passengers: "+passengers;}

}

Defining a Subclass

public class VehicleProjectInheritance { public static void main(String[] args) { Car c = new Car("Honda", 455.0f, 4); System.out.println(c.print()); }}

"is-a" and the "has-a" relationship

o "Is-a" represents inheritance.o In an "is-a" relationship, an object of a subclass can also

be treated as an object of its superclass.o “Has–a” represents the encapsulation, i.e: The relation

between object and its members.

"is-a" and the "has-a" relationship

Vehicle Class SuperClass

Car Class SubClass

Honda is a car & Honda is a vehicle

Object of sub is also an object of super

THANKS!

Any questions?You can find me at:

Fb/mahmoudRAlfarraStaff.cst.ps/mfarraYoutube.com/mralfarra1@mralfarra

قال الله تعالى:)وه0و الذي يقب0ل التوب0ة ع0ن

عباده ويعفو عن السيئات(

Lecture Let’s focus on Superclass’s Constructor

2

Are superclass’s Constructor Inherited?

o No. They are not inherited.o They are invoked explicitly or implicitly. o Explicitly using the super keyword.

o A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass.

Superclass’s Constructor Is Always Invoked

o A constructor may invoke an overloaded constructor or its superclass’s constructor. If none of them is invoked explicitly, the compiler puts super)( as the first statement in the constructor. For example,

public A(double d) { // some statements }

is equivalent to

public A(double d) { super(); // some statements }

public A() { }

is equivalent to

public A() { super(); }

Using the Keyword super

o The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways:1. To call a superclass constructor2. To call a superclass method

Constructor Chaining

o Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain.

o This is known as constructor chaining.

public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

Trace Execution

Overriding Methods in the Subclass

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

o This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the toString method defined in GeometricObject */ public String toString() { return super.toString() + "\nradius is " + radius; } }

Overriding vs. Overloading public 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); } }

public 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); } }

Overriding vs. Overloading

o The example above show the differences between overriding and overloading.

o In )a(, the method p)double i( in class A overrides the same method in class B.

o In )b(, the class A has two overloaded methods: p)double i( and p)int i(.

o The method p)double i( is inherited from B.

Full Example

Student

Post Graduat

e

Graduate

• Have part time hours • Have a field training

Full Example

o Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain.

o This is known as constructor chaining.

Full Example

Methods of a subclass cannot directly access private members of their superclass.

With inheritance, the common instance variables and methods of all the classes in the hierarchy are declared in a superclass.

Use the protected access modifier when a superclass should provide a method only to its subclasses and other classes in the same package, but not to other clients.

Full Example

A subclass is more specific than its superclass and represents a smaller group of objects.

A superclass's protected members have an intermediate level of protection between public and private access. They can be accessed by members of the superclass, by members of its subclasses and by members of other classes in the same package.

A compilation error occurs if a subclass constructor calls one of its superclass constructors with arguments that do not match the superclass constructor declarations.

Full ExampleIn Java, the class hierarchy begins with class Object (in package java.lang), which every class in Java directly or indirectly extends.

Invoking a superclass constructor’s name in a subclass causes a syntax error.

Java requires that the statement that uses the keyword super appear first in the constructor.

If a class is designed to be extended, it is better to provide a no-arg constructor to avoid programming errors.

Practices

Practice 1Using charts, What is Inheritance ?

Practice 2Compare between the Types of Inheritance and which of them supported in java.

Practice 3By UML class, explain the concepts of Superclasses and Subclasses.

Practice 4Give 3 examples to explain Direct & Indirect Superclasses.

Practice 5Diffrenciate between "is-a" and the "has-a" relationship.

Practice 6Explain the Constructor Chaining using code.

Practices

Practice 7True or false? You can override a

private method defined in a superclass.

You can override a static method defined in a superclass.

A subclass is a subset of a superclass.

Practice 8Write simple code: What keyword do

you use to define a subclass?

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

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

Practice 9 (In groups)

Define The

GeometricObject,

Circle and Rectangle,

based on the

GeometricObject is the

superclass for Circle

Rectangle .

THANKS!

Any questions?You can find me at:

Fb/mahmoudRAlfarraStaff.cst.ps/mfarraYoutube.com/mralfarra1@mralfarra