0% found this document useful (0 votes)
5 views41 pages

Inheritance

Uploaded by

23020661
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views41 pages

Inheritance

Uploaded by

23020661
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Inheritance

Vũ Thị Hồng Nhạn

([email protected])

Dept. of Software Engineering, UET

Vietnam National Univ., Hanoi


Content
 Encapsulation
 i.e., a class contains everything it needs and nothing more!

 Inheritance is
 Passing down traits or characteristics from a parent to their child like
skin, hair color
 Inheritance enable polymorphism

 Polymorphism (multiple shapes or forms)


 References to objects can exists under multiple variables names.
 These references can point to the same object in memory, allowing you
to group or treat different objects as if they belong to a certain type or
group

10/9/2024 Inheritance Page 2


Example
Building a bank account manager
 Assume you have 3 different types of accounts

 Checking account
 Saving account
 Certificate of deposit

 They all share similar information like the account number and
the balance in them
 But they also have different attributes

10/9/2024 Inheritance Page 3


Example…

Building a bank account manager

10/9/2024 Inheritance Page 4


Example…

Building a bank account manager


 Basically you can implement that in one single class in java

  that means, everything is included in that class!

10/9/2024 Inheritance Page 5


Example…

Building a bank account manager


 Another way is to create a class for each account type
 each class would only contain the fields and methods that make
sense for that class

10/9/2024 Inheritance Page 6


Example…

Problem caused by a change!


 If we decide to include the bank code  have to change that in all
three classes

 This simple change could be a nightmare in a production-sized


project!

10/9/2024 Inheritance Page 7


Example…

Inheritance is the solution


BANK ACCOUNT
Account:
Balance:

extends extends extends

CHECKING ACCOUNT SAVING ACCOUNT CREDIT ACCOUNT


Limit Transfers Expiry

10/9/2024 Inheritance Page 8


Inheritance
 First, start by creating the bank account class
class BankAccount{
String acctNumber;
double balance;
}
 Next, create another class and points to extend that basic class by adding
the phrase “extend” and then the class name

class Checking extends BankAccount{


double limit;
}

10/9/2024 Inheritance Page 9


Inheritance…

class BankAccount{
String acctNumber;
double balance;
parent
}

class Checking extends BankAccount{


double limit; child
}

10/9/2024 Inheritance Page 10


Inheritance…

class SavingAccount extends BankAccount{


int transfers;
}
child

class COD extends BankAccount{


Date expiry; child
}

10/9/2024 Inheritance Page 11


Conclusion
 From that example, you can see that using inheritance has allowed
us to minimize repeating any code

 While still having the flexibility and the good design of separate
account classes

10/9/2024 Inheritance Page 12


Polymorphism
what is polymorphism?
 Polymorphism in the context of object-oriented programming refers to the
ability of a single entity (an object) to take multiple forms

 Allows objects of different classes to be treated as objects of a common


superclass or interface

 E.g., A class extends another class, an object of the subclass can be treated
as an instance of both its own class and its parent class

 This allows a single object to be used in different ways depending on the


context, typically through method overriding or interface implementation

10/9/2024 Inheritance Page 14


Example
PERSON
String name
String email

extends extends

STUDENT TEACHER
double grade int level
int year int yearOfExp

10/9/2024 Inheritance Page 15


Example…
 If you were to create an object of type student, you can start
declaring it using the student type and initialize it using the student
constructor

 Student student = new Student();

 Do similar if you want to create an object of type teacher

 Teacher teacher = new Teacher();

10/9/2024 Inheritance Page 16


Example…
If Student student = new Student();
Person

Teacher teacher = new Teacher();

Person student = new Student();i

Person teacher = new Teacher();

10/9/2024 Inheritance Page 17


Bags & items example

Crossbow
Coins
int power
int amount int weight
int weight

Key
RareItem
int code
int value
int weight
int weight

10/9/2024 Inheritance Page 18


Bags & items example

items
Item
int weight
extends

extends
Coins Crossbow
int amount extends extends int power

RareItem Key
int value int code

10/9/2024 Inheritance Page 19


Bags & items example

Bags
public class Bag{
Item[] list;
int count;
int currentWeight;
Bag(){list = new Item[100];
count =0; currentWeight =0;
}
boolean canAddItem(Item item){…}
void addItem(Item item){…}
}

10/9/2024 Inheritance Page 20


Bags & items example

Bags…
boolean canAddItem(Item item){
if(currentWeight + item.weight >20)
return false;
else
return true;
}
void addItem(Item item){
list[count]= item;
}

10/9/2024 Inheritance Page 21


Bags & items example…
public static void main(String[] args){
CrossBow crossbow = new Crossbow();
if(bag.canAddItem(crossbow)
bag.addItem(crossbow);//can add crossbow without being casted
}

10/9/2024 Inheritance Page 22


Overriding methods
Chess game example
 Class for each piece of type
 Each chess piece (e.g., King, Queen…) is
represented by a specific class that inherits Rook
from a base class named Piece

 Piece class (base class)


 Contains all attributes and methods that are common to all pieces (e.g., color, position,
potentially methods to calculate moves or capture status)

 Board class
 Represents the chessboard by 2D array of Square objects (Square[][] board)

 Manage the state of the chessboard, including the pieces on each square
 Allow the game to place and move pieces and keep track of which squares are
occupied

10/9/2024 Inheritance Page 24


Chess game example…

Other classes
class Board{
Square [][] board;
Game(){
board = new Piece[8][8];
}…..
}

 Position class
 Represents the coordinate of a square on the chessboard

class Position{
int row; int column;
Position(int row, int column){
this.row=row; this.column=column; } ….
}

10/9/2024 Inheritance Page 25


Chess game example…

Other classes…
 Square class
 Represents a single square on the chessboard, which can either be empty or
occupied by a piece

class Square{
Position position;
Piece occupant;
….
}
 Pieces class
 serves as the base class for all chess pieces, defining common
attributes and behaviors that each piece type (King, Queen,…) shares

10/9/2024 Inheritance Page 26


Chess game example…

Other classes…
 E.g., it will be useful to have a
method that checks if a potential
movement of a piece is valid one
 validMove() is used to get
valid moves for the piece
 …..
 isValidMove() to check if a
piece’s move is valid

10/9/2024 Inheritance Page 27


Chess game example…

Other classes…
class Piece{
Position position;
…….
boolean isValidMove(Position newPosition){
if(newPosition.row > 0 && newPosition.column >0 && newPosition<8
&& newPosition.column <8)
return true;
else
return false;
}
}

10/9/2024 Inheritance Page 28


Chess game example…

Other classes…
 Since each of the child class inherits from that Piece class, each will
automatically include this method, which means you can call it from any
of those classes directly

 E.g.,
Queen queen = new Queen();
Position testPosition = new Position(3,3);
if(queen.isValidMove(testPosition))
System.out.println(“Yes, you can move there”);
else
System.out.println(“Nope, cannot move there”);

10/9/2024 Inheritance Page 29


Chess game example…
 Till now, we’re just be able to check the validity of the movement of a
piece on the board

 Each piece type has a different pattern of allowed movements, which


means that each of those child classes need to implement the
isValidMove() method differently

 Luckily, java not only offers a way to inherit a method from a parent class
but also modify it to build your own custom version of it

10/9/2024 Inheritance Page 30


Overriding
 When a class extends another class, all public methods
declared in that parent class are automatically included in the
child class without any additional effort

 However, you are allowed to override any of those methods

 Overriding basically means re-declaring them in the child class and


then re-defining what they should do

10/9/2024 Inheritance Page 31


the chess example
 The Rook class inherits the Piece class that already includes a definition
of the isValidMove() method

 However, in the Rook class, a new specialized version of


isValidMove() is implemented to handle move validation specially
for the rook piece according to its movement (i.e., vertically or
horizontally moving on the board)

10/9/2024 Inheritance Page 32


The chess example…
class Rook extends Piece{
boolean isValidMove(Position newPosition){
if(newPosition.column==this.position.column ||
newPosition.row==this.position.row)
return true;
else
return false;
}
}

 Notice how both method declarations are identical, except that the
implementation in the child class has different code customizing the validity check
for the Rook piece

10/9/2024 Inheritance Page 33


The chess example…
 Basically it’s checking that the new position of the rook

 has the same column value as the current position (which means it’s trying to
move up or down )

 or has the same row position which means it has moved sideways,

  both valid movements for a Rook piece

 Remember that this.position.column and this.position.row are the


local fields of the Rook class holding the current position of that piece

10/9/2024 Inheritance Page 34


The chess example…
 Can do the same for all the other piece types, e.g., the Bishop class would have
slightly different implementation
 Since Bishop moves diagonally, we want to check that #vertical steps is equal to
#horizontal steps.
class Bishop extends Piece{
boolean isValidMove(Position newPosition){
if(Math.abs(newPosition.column – this.position.column) ==
Math.abs(newPosition.row- this.position.row))
return true;
else
return false;
}
}

10/9/2024 Inheritance Page 35


The chess example…
 Now let’s try to override that method for the Queen class
 Queen can move diagonally or in straight lines

 What can we do?


1. In the Queen class, override the isValidMove() method
2. First, call the parents’ isValidMove() to check for the boundaries
3. Add more code to check the queen’s specific move validity

10/9/2024 Inheritance Page 36


Super
Super?
 Note that once you override a method,

 you basically ignore everything that was in the parent class

 It’s possible not to throw away the parent implementation

 ADD the extra checks for each child class individually

 To re-use the parent method in the child class by using the “super”
keyword, followed by a dot and then the method name

 super.isValidMove(position);

10/9/2024 Inheritance Page 38


Super…
 That means, in each of the child classes,

 before you get to check the custom movement, you can check if
super.isValidMove(position) has returned false

 If so, then no need to do any more checks and immediately return false

 otherwise, continue checking

 The new implementation for the Rook class will look like….

10/9/2024 Inheritance Page 39


example
class Rook extends Piece{
boolean isValidMove(Position newPosition)
if(!super.isValidMove(position)) //check for the board bounds
return false;
//check for the specific rock movement

if(newPosition.column==this.position.column &&
newPosition.row==this.position.row)
return true;
else
return false;
}

10/9/2024 Inheritance Page 40


example…
class Rook extends Piece{
//default constructor
public Rook(){
super(); //this will call the parent’s constructor
this.name=“rook”;
}
}
Note: if a child’s constructor doesn’t explicitly call the parent’s
constructor using super, the java compiler automatically inserts a
call to the default constructor of the parent class
If the parent class doesn’t have a default constructor, you’ll get a
compiler-time error

10/9/2024 Inheritance Page 41

You might also like