INF101: Object-Oriented Programming - Mitt UiB

75
INF101: Object-Oriented Programming Lecture 11: Inheritance

Transcript of INF101: Object-Oriented Programming - Mitt UiB

INF101: Object-Oriented Programming

Lecture 11: Inheritance

Welcome to INF101 – Lecture 11!

• Previously:

– Data structures

– Collections

Collections

Image source: https://www.javatpoint.com/collections-in-java

Image source: https://dzone.com/articles/an-introduction-to-the-java-collections-framework

Implementing your own data

structure?

• Reasons why:

– Helps to learn how things work

– No suitable API available

• Reasons why not:

– Use of existing saves time

– Probably better designed and tested (edge

case bugs)

Four main concepts in OOP

• Encapsulation

• Abstraction

• Inheritance

• Polymorphism

Four main concepts in OOP

• Encapsulation

• Abstraction

• Inheritance

• Polymorphism

Inheritance

• Eliminate redundant code by inheriting properties

and methods from a superclass

• New class that derives from superclass is

subclass

• Subclass automatically gets all fields and methods

from superclass

• Implements ‘is-a-type-of’ relationships

Also previously

• Interfaces: classes can implement to fulfil

‘contract’

• Cannot be instantiated

• Only method signatures, except default methods

Interfaces

• Similar to abstract class, but can only have

abstract methods and final variables (constants

that cannot be modified)

• A class implements an interface by providing

code for each declared method

Our pond used interfaces to make

it easy to add new pond-dwellers<<interface>>

IPondObject

Duck Frog

step()

draw(painter)

Interfaces

• All methods have no body (abstract)

• Implementation of methods is left to classes that

implement an interface

• Implementing class has to implement every

method specified in the interface by contract

Interfaces + Inheritance

http://www.cs.sjsu.edu/~pearce/modules/lectures/oop/basics/interfaces.htm

Today

• More about inheritance

Questions?

Inheritance

Inheriting (non Computer Science

edition)

Inheriting (non Computer Science

edition)

• Characteristics:

– Hair color

(natural blondes!)

• Behavior:

– Introverted

– Headstrong

– Extreme intelligence ;)

• Can also inherit things if he passes away

Our relation

André Smit

Noeska Smit

Our relation in Java

André Smit

Noeska Smit

We’ve seen this before!

Image source:

https://en.wikipedia.org/wiki/Subtyping#/media/File:Inheritance.svg

Inheritance

• Subclass takes on all behavior and attributes of super class

• Subclass can add features to the ones inheritedby defining own methods and fields

• Subclass can change inherited behavior by having own implementation of inherited methods

• Best used for is-a-type-of relations (a duck is a type of bird)

Exercise

• Think back of our bird superclass,

and duck and penguin subclasses.

– Think of fields and methods that

are common to both ducks and

penguins

– Think of fields and methods that

are different between ducks and

penguins

Exercise

• Think back of our bird superclass,

and duck and penguin subclasses.

– Think of fields and methods that

are common to both ducks and

penguins

– Think of fields and methods that

are different between ducks and

penguins

Example answers

• Common fields: numberoffeet, beaklength,

wingspan, ….

• Common methods: walk, dive, …

• Different fields: ?

• Different methods: fly, …

Penguins vs Ducks

Image source: https://www.abc.net.au/news/2010-08-27/a-penguin-fights-with-a-duck-in-a-zoo-enclosure/956536

Another example: board games

• Common features:

– Playing board with locations for players

– Players are represented by objects

– Players take turns during game

• Each game has these basics, but also adds:

– Monopoly has Chance and Community chest cards, properties, houses, hotels, and money

Inheritance SyntaxSuperclass

Subclass

What happens with inheritance?

• When a subclass inherits from a superclass

(extends keyword in subclass), all public

members of the superclass are available to a

subclass

• Private members are not! They become a part of

the derived class, but you cannot access them

from the derived class

Inheritance ‘rules’

• Subclass inherits all members (fields and

methods) from superclass (not constructor)

• You can override a method by declaring a new

method with the same signature in the subclass

• Visibility (public or private) of members inherited

from superclass is the same in the subclass

• You can add more methods of fields to a subclass

Special type of visibility:

Protected

• In addition to private or public, there is also the

protected visibility level

• Hides fields and methods from other classes, but

makes them available to subclasses

• This means a subclass can call the superclass

protected methods, but other classes cannot

Overriding methods

• Subclass overrides a method if it has the same

signature as a public method of the base class

• Same signature: same return type, same name,

same number and type of parameters

• Also:

– Class must extend the class that defines the

method that you want to override

– Method must be public in superclass

Override pro tip

• Use the @Override annotation to make sure your

method is actually overriding something

Exercise

Exercise: What gets printed?

Exercise

Exercise Answer

More fun

Adding to BaseBall class:

Then in test:

Questions?

Break

Inheritance Variants• Single Inheritance: One class inherits from another

class

• Hierarchical Inheritance: Multiple classes inherit from another class

• Multi-Level Inheritance: A class derived from a superclass can be used as the superclass for another subclass

Inheritance Variants

What about this one?

I have a mom too ☺

So it’s more like…

André Smit

Noeska Smit

Corrie Smit

Can we do this in Java?

André Smit

Noeska Smit

Corrie Smit

Multiple Inheritance is not allowed

in Java!

• What if both superclasses implement the same methods? Which one to call?

• Read more here: https://www.geeksforgeeks.org/java-and-multiple-inheritance/

Implementing multiple interfaces

is fine and common though!

• Interfaces cannot have fields (state) and cannot be instantiated, unlike superclasses, so no problems with multiple inheritance of state

• Read more here: https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html

this

• The this keyword allows you to refer to the

current object instance (for instance to distinguish

local variables/parameters and class fields with

the same name

super• The super keyword allows you to refer to the instance

of the super class

• Can also use it to call a constructer of the superclass *must call it if there are no default constructors for both! (the constructor with no input parameters)

About those constructors• When you create an instance of a subclass, Java

automatically calls the constructor of a superclass before executing the subclass constructor

• You can also explicitly call the superclass constructor using super.Classname(parameters) if you want to pass some parameters, but it has to be the first statement of the subclass constructor

• If you don’t call the superclass constructor using super, the base class must have a default constructor, if not: compile error

• If the superclass is a subclass, it also calls the constructor its superclass first, chaining all the way up

final

• We’ve seen final used with variables: creates a

constant that you cannot change

• But you can also create final methods and

classes!

final methods

• Cannot be overridden by subclasses

• Private methods are automatically final, since

subclasses cannot see them ☺

final classes

• Cannot be used as a superclass

• No one can inherit from BaseBall then

• All of its methods are then considered final too (no

class could possible override)

Casting up

• Casting up is automatically done by Java

• When you need a Ball as method input parameter,

and provide a BaseBall, this is fine

Casting down

• You cannot use a Ball object where you need a

BaseBall:

, then you need to cast it

Imagine

• If you need both a toss method for BaseBall and

SoftBall objects, don’t create toss(BaseBall bb)

and toss(SoftBall sb), but make a toss(Ball b)

instead

• But what if the behavior is different depending on

the ball type?

Instanceof operator

• If you need to know which type a particular object,

you can use the instanceof operator

Testing

Exercise: what gets printed?

Exercise: solution

Remembering our friend Object• All classes inherit from Object (even if they don’t state

it)

• Basic functionality, for example:

– toString()

– equals(Object obj)

– hashCode()

Read more at ‘our library’ the Java API: https://docs.oracle.com/javase/8/docs/api/java/lang/Object.htmland at this tutorial: https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html

A bit more on equals

• Reflexive: x.equals(x) returns true

• Symmetric: if x.equals(y) returns true, then also

y.equals(x) returns true

• Transitive: if x.equals(y) and y.equals(z) both

returns true, then also x.equals(z) should return

true

So ‘secret’ inheritance

Delegation pattern• Including an instance of one class in another class

• Example: you want to make a DuckCollection that behaves like an ArrayList

– You could extend the ArrayList class, but…

– Could also declare a class field of type Arraylist in your DuckCollection class

• Instead of writing code that implements ArrayListfunctions, you delegate that to the ArrayList object

Polymorphism

• Using superclass variables to refer to subclass objects

• Keeping track of which subclass an object is

• Use overridden methods of the subclass, even if subclass is not known at compile time

• See also:https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html

Questions?

The first obligatorisk assignment

will be released next week!

• You can prepare by working on the labs

• You can check out the quiz on Mitt to test your

knowledge (interfaces anyone?)

• You can come to the group sessions and ask any

questions you may have

The Weeky Labs

• Best preparation for compulsory assignment

which is released next week!

165

134

97

20 7 4

1 2 3 4 5 6

Labs Completion

Specifically

• To understand how to hand in the assignment, you have to do lab 1 and 3

• The semester assignment will be easier to solvewith the theory and skills from the labs, inparticular of lab 3 and 4

Important: if you have not tried GitLab (retting.ii.uib.no) and pushing and handing in assignments, do it now, you will not get help with this at the deadline (visit group hours earlier instead)

What can you do?

• Work on the labs linked from our wiki (6 labs are up!)

• A quiz on Mitt UiB (check if you are ready for

compulsory assignment 1 from next week!)

• Read Book 3, Chapter 4 “Java All-in-One for

Dummies” by Doug Lowe (https://ebookcentral-proquest-

com.pva.uib.no/lib/bergen-ebooks/detail.action?docID=1688016)

• Check out the Java tutorial on inheritance: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

What’s next?

• Next lecture TBA, rescheduling a bit

• Topic: more inheritance, class invariance

Thanks!