Java OOP Exam Assignment
Course: Object-Oriented Programming (Java)
Topic: Inheritance & Polymorphism
Std Name : Hossein Saghir
Std ID : 111674
Instructor : Dr Samer Sendyan
PART A :
Inheritance is an Object-Oriented
Programming (OOP) concept where one class
Inheritance
(child/subclass) acquires the properties and
behaviors (fields and methods) of another
class (parent/superclass).
It promotes code reusability and method
overriding.
Example About Inheritance Person
-Person_ID:(int)
-Person_Name:(String)
Pkg{ …
Public class Person{
private int Person_ID ; +Person(Parameters)
private String Person_Name ; +Getters and setters
methods
+toString():String
public Person (Person_ID , Person_Name){
this.Person_ID=Person_ID ;
this.Person_Name= Person_Name ;
}
//Getters and setters methods
…
public String toString(){
return ‘’[The id is: ’’+Person_ID+’’ , and the name is:’’+Person_Name+’’, ’’ ;
}
Public class Student extends Person {
private String Std_Major ;
private int Std_Year ;
Student Doctor
public Student(int id , String name , String major , int year ){
SetId(id) ;
SetName(name) ; -Std_Major :(String) ….
this.Std_Major = major ; -Std_Year:(int)
…
this.Std_Year = year ;
} +Student(Parameters)
//Getters and setters methods +Getters and setters
@Override methods
public String toString(){ +toString():String
return [Link]()+ ’’ the major of this Student is :’’+Std_Major+ ‘’
and the year is :‘’+Std_Year+’’]’’ ;
}
}
}
PART A :
Polymorphism is a Greek word . Poly means
Polymorphism many and morphe means form .So
polymorphism means “Having many forms” .
i.e. It’s a reference from a superclass can refer
to objects from different types provided that
these types are from subclasses of the
superclass .
Example About Polymorphism
If we have a Geometric Object reference g1 then w can write any of the following statements :
g1=new GeometricObject(“Red”, true) ; //g1 refers to a Geometric object
g1=new Circle (‘Red” ,true , 2.0); //g1 refers to a Circle object
g1=new Rectangle (“Red” , true , 5.0 , 6.0 ) ; //g1 refers to a Rectangle object
▪ Hence , g1 can refer to different types , i.e. it has many forms
PART A :
Method Overriding occurs when a subclass
(child class) provides a specific
implementation for a method that is already
defined in its superclass (parent class) .
Runtime polymorphism (also known as
Dynamic Method Dispatch) is the mechanism
where a call to an overridden method is
resolved at runtime rather than compile-time.
PART B : Programming Task
Design a Vehicle Management System using inheritance and polymorphism.
Step 1: Create abstract class Vehicle with attributes (brand, speed) and methods start(), stop(), and abstract
calculateFuelEfficiency().
Step 2: Create subclasses Car, Bike, Truck and override methods.
Step 3: Demonstrate polymorphism using an array of Vehicle objects