Understanding Inheritance, Polymorphism, and Interfaces in Java: A Comprehensive Guide, Exercises of Computer science

An in-depth explanation of Inheritance, Polymorphism, and Interfaces in Java. It covers the fundamental principles, nomenclature, mechanics, and real-life applications of these concepts. Learn how they model real-world relationships, allow code reuse, and enable polymorphic behavior.

Typology: Exercises

2021/2022

Uploaded on 09/27/2022

andreasphd
andreasphd 🇬🇧

4.7

(28)

287 documents

1 / 9

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Inheritance, Polymorphism, and Interfaces 1
Advanced Placement
Computer Science
Inheritance and Polymorphism
What’s past is prologue.
Don’t write it twice — write it once and reuse it.
Bekki George
James E. Taylor HS, Katy
Inheritance, Polymorphism, and Interfaces 2
Main Tenants of OO Programming
Encapsulation
abstraction, information hiding, responsibility
driven programming
Inheritance
code reuse, specialization "New code using old
code."
Polymorphism
do X for a collection of various types of objects,
where X is different depending on the type of
object
"Old code using new code."
Inheritance, Polymorphism, and Interfaces 3
Explanation of Inheritance
1 of the fundamental principles of OOP
allows code reuse
Models the IS-A relationship
a student is-a person
an undergraduate is-a student
a rectangle is-a shape
a rook is-a piece
Contrast with the Has-A relationship (or uses a)
a student has-a name
a rook has-a position
a Stack uses a List
Is-a relationships indicate inheritance, has-a
relationships indicate composition (fields)
Inheritance, Polymorphism, and Interfaces 4
Nomenclature of Inheritance
The extends keyword is used to specify which
preexisting class a new class is inheriting from
public class Student extends Person
Person is said to be
the parent class of Student
the super class of Student
the base class of Student
an ancestor of Student
Student is said to be
a child class of Person
a sub class of Person
a derived class of Person
a descendant of Person
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Understanding Inheritance, Polymorphism, and Interfaces in Java: A Comprehensive Guide and more Exercises Computer science in PDF only on Docsity!

Inheritance, Polymorphism, and Interfaces

1

Advanced PlacementComputer Science

Inheritance and Polymorphism^ What’s past is prologue.Don’t write it twice — write it once and reuse it.

Bekki George

James E. Taylor HS, Katy

Inheritance, Polymorphism, and Interfaces

Main Tenants of OO Programming^ Encapsulation– abstraction, information hiding, responsibilitydriven programming^ Inheritance– code reuse, specialization "New code using oldcode."^ Polymorphism– do X for a collection of various types of objects,where X is

different

depending on the type of

object– "Old code using new code."

Inheritance, Polymorphism, and Interfaces

3

Explanation of Inheritance 1 of the fundamental principles of OOP– allows code reuse Models the

IS-A^ relationship

– a student is-a person– an undergraduate is-a student– a rectangle is-a shape– a rook is-a piece Contrast with the

Has-A

relationship (or uses a)

– a student has-a name– a rook has-a position– a Stack uses a List Is-a relationships indicate inheritance, has-arelationships indicate composition (fields)

Inheritance, Polymorphism, and Interfaces

Nomenclature of Inheritance The^ extends

keyword is used to specify which

preexisting class a new class is inheriting from^ public class Student extends Person^ Person is said to be– the parent class of Student– the super class of Student– the base class of Student– an ancestor of Student^ Student is said to be– a child class of Person– a sub class of Person– a derived class of Person– a descendant of Person

Inheritance, Polymorphism, and Interfaces

5

The Mechanics of Inheritance Java is a pure object oriented language all code is part of some class all classes, except one, must inherit fromexactly one other class The^ Object

class is the

cosmic super class

-^ The

Object

class does not inherit from any other class

-^ The

Object

class has several important methods:

toString

,^ equals

,^ hashCode

,^ clone

,^ getClass

implications:– all classes are descendants of

Object

-^ all classes, and thus all objects, have a

toString

equals

,^ hashCode

,^ clone

, and^ getClass

method

-^ toString

,^ equals

,^ hashCode

,^ clone^

normally overridden

Inheritance, Polymorphism, and Interfaces

Inheriting from a Class

If a class header does not include theextends clause the class extends the Object

class by default

public class Card– Object

is an ancestor to all classes

– it is the only class that does not extend someother class A class extends exactly one other class– extending two or more classes is

multiple

inheritance.

Java does not support this directly,

rather it uses

Interfaces

Inheritance, Polymorphism, and Interfaces

7

Implications of Inheritance The sub class gains all of the behavior (methods) and dataregarding state (instance variables) of the super class

and

all ancestor classes Sub classes can:– add new fields– add new methods–^ override

existing methods (change behavior)

Sub classes may not– remove fields– remove methods Note, even though an object may have instance variablesfrom its parent they may not be accessible by the code ofthe child class if the fields are private

Inheritance, Polymorphism, and Interfaces

The Real PictureFields from Object classInstance variablesdeclared in ObjectFields from String classInstance Variablesdeclared in StringBehaviors (methods) from String classand Object class.

A Stringobject

Inheritance, Polymorphism, and Interfaces

13

A ClosedShape class

public

class^

ClosedShape {^ private

int^ iMyX; private

int^ tMyY; public

ClosedShape() {^ this(0,0);

public

ClosedShape

(int^

x,^ int

y)

{^ iMyX

=^ x;iMyY =^ y; } public

String

toString() {^ return

"x:^ "^

+^ iMyX

+^ "^ y:

"^ +^ iMyY;

public

int^ getX(){

return

iMyX;

public

int^ getY(){

return

iMyY;

}//^ Other

methods

not^ shown

Inheritance, Polymorphism, and Interfaces

Constructors

Constructors handle initialization of objects When creating an object with one or more ancestors (everytype except Object) a chain of constructor calls takes place The reserved word

super

may be used in a constructor to

specify which of the parent's constructors to call– must be first line of constructor if no parent constructor is explicitly called the default, 0parameter constructor of the parent is called– if no default constructor exists a syntax error results If a parent constructor is called another constructor in thesame class may no be called– no^ super();this();

allowed. One or the other, not both

  • good place for an initialization method

Inheritance, Polymorphism, and Interfaces

15

A Rectangle Constructor

public class Rectangle extends ClosedShape{^ private int iMyWidth;private int iMyHeight;public Rectangle(int width, int height,

int x, int y)

{^ super(x,y);// calls the 2 int constructor in// ClosedShapeiMyWidth = width;iMyHeight = height;} // other methods not shown}

Inheritance, Polymorphism, and Interfaces

A Rectangle Class public class^ Rectangle

extends

ClosedShape

{^ private

int^ iMyWidth;private int^ iMyHeight;public Rectangle(){ this(0,^ 0);} public Rectangle(int

width,^

int^ height)

{^ this(width,

height,

0,^ 0); } public^ Rectangle(int

width,^

int^ height, int^ x,^ int

y) {^ super(x,

y); iMyWidth

=^ width; iMyHeight

=^ height; } public^ String

toString() {^ return

super.toString()

+^ "^ width:

"^ +^ iMyWidth

+^ "^ height:

"^ +^ iMyHeight; }}

Inheritance, Polymorphism, and Interfaces

17

Initialization method public class Rectangle

extends ClosedShape

{^ private int iMyWidth;private int iMyHeight;public Rectangle(){^ init(0, 0);} public Rectangle(int width, int height){^ init(width, height);} public Rectangle(int width, int height,

int x, int y){ super(x, y);init(width, height);} private void init(int width, int height){ iMyWidth = width;iMyHeight = height;}

Inheritance, Polymorphism, and Interfaces

Overriding methods

any method that is not

final

may be

overridden by a descendant class– overriding is a replacement of a behavior– overloading is the addition of a behavior^ same signature as method in ancestor^ may not reduce visibility^ may use the original method if simply want toadd more behavior to existing– also called

partial overriding

The Rectangle class– adds data, partially overrides

toString

Inheritance, Polymorphism, and Interfaces

19

The Keyword

super

super

is used to access something (any protected or

public field or method) from the super class that hasbeen overridden Rectangle's

toString

makes use of the

toString

in

ClosedShape my calling

super.toString()

without the super calling

toString

would result in

infinite recursive calls Java does not allow nested supers^ super.super.toString() results in a syntax error even though technically thisrefers to a valid method, Object's

toString

Rectangle

partially

overrides ClosedShape's

toString

Inheritance, Polymorphism, and Interfaces

What Can Rectangles Do? Rectangle

r1^ =^

new^ Rectangle(); Rectangle

r2^ =^

new^ Rectangle(10,

Rectangle

r3^ =^

new^ Rectangle(10,

15,^ 2,

System.out.println(

r1^ );

System.out.println(

r2^ );

System.out.println(

r3^ );

int^ a^

=^ r1.getX()

+^ r1.getY(); ClosedShape

s^ =^ new

Rectangle(5,

10,^ 3,

System.out.println(

s.toString()

a^ +=^ s.getX();ClosedShape[]

sList

=^ new

ClosedShape[3];

sList[0]

=^ new

ClosedShape(5,

sList[1]

=^ new

Rectangle(10,

25,^ 10,

sList[2]

=^ r2; for(int

i^ =^ 0;

i^ <^ sList.length;

i++)

System.out.println(

sList[i].toString()

Inheritance, Polymorphism, and Interfaces

25

A^ Circle Class

public

class

Circle

extends

ClosedShape

{^ int

iMyRadius;public^ Circle(){ this(1);

public

Circle(int

radius) {^ iMyRadius

=^ radius; } public

Circle(int

radius,

int^ x,

int^ y)

{^ super(x,y);iMyRadius

=^ radius; } public

int^ getArea() {^ return

Math.PI

*^ iMyRadius

*^ iMyRadius;

public

String

toString() {^ return

super.toString()

+^ "^ radius:

"^ +^ iMyRadius;

Inheritance, Polymorphism, and Interfaces

Polymorphism in Action public class UsesShapes{ public static void go(){ ClosedShape[] sList = new ClosedShape[10];int a, b, c, d;int x;for(int i = 0; i < 10; i++){^ a = (int)(Math.random() * 100);b = (int)(Math.random() * 100);c = (int)(Math.random() * 100);d = (int)(Math.random() * 100);x = (int)(Math.random() * 3 );if( x == 0 )

sList[i] = new Rectangle(a,b,c,d);else if(x == 1)sList[i] = new Square(a,c,d);elsesList[i] = new Circle(a,c,d); }int total =0;for(int i = 0; i < 10; i++){^ total += sList[i].getArea();System.out.println( sList[i] );}} }

Inheritance, Polymorphism, and Interfaces

27

The Kicker

We want to expand our pallet of shapes Triangle could also be a sub class ofClosedShape.– it would

inherit

from ClosedShape

public int getArea(){ return 0.5 * iMyWidth * iMyHeight;} What changes do we have to make to thecode on the previous slide for totaling areaso it will now handle Triangles as well? Power.

Inheritance, Polymorphism, and Interfaces

Object Variables

The above code works if Rectangle extendsClosedShape An object variable may point to an object of itsbase type or a descendant in the inheritance chain– The is-a relationship is met. A Rectangle object is-ashape so

s^ may point to it

This is a form of

polymorphism

and is used

extensively in the Java

Collection

classes

Rectangle r = new Rectangle(10, 20);ClosedShape s = r;System.out.println("Area is " + s.getArea());– Vector, ArrayList are lists of Objects

Inheritance, Polymorphism, and Interfaces

29

polymorphism allows s to point at a Rect object butthere are limitations The above code will not compile Statically,

s^ is declared to be a shape

  • no changeWidth method in Shape class– must

cast^ s^

Type Compatibilityto a^ Rectangle

Rectangle r = new Rectangle(5, 10);ClosedShape s = r;s.changeWidth(20); // syntax errorRectangle r = new Rectangle(5, 10);Shape s = r;((Rectangle)s).changeWidth(20); //Okay

Inheritance, Polymorphism, and Interfaces

Problems with Casting

The following code compiles but a Class CastException is thrown at runtime Casting must be done carefully and correctly If unsure of what type object will be the use the instanceof

operator or the

getClass()

Rectangle r = new Rectangle(5, 10);Circle c = new Circle(5);Shape s = c;((Rectangle)s).changeWidth(4); method^ expression instanceof ClassName

Inheritance, Polymorphism, and Interfaces

31

Multiple Inheritance

Inheritance models the "is-a" relationshipbetween real world things one of the benefits is code reuse,completing programs faster, with less effort in the real world a thing can have "is-a"relationships with several other things– a Graduate Teaching Assistant is-a GraduateStudent. Graduate Teaching Assistant is-aFaculty Member– a Student is-a Person. a Student is aSortableObject

Inheritance, Polymorphism, and Interfaces

Interfaces

A Java

interface

is a "pure abstract

class".– Design only, no implementation.^ Interfaces are declared in a way similar toclasses but– consist only of public abstract methods– public final static fields^ A Java class extends exactly one otherclass, but can implement as many interfacesas desired