Object-Oriented Programming: Computer Science Year II
Object-Oriented Programming: Computer Science Year II
Object-Oriented Programming: Computer Science Year II
Programming
Computer Science Year II
Compiled by: Gebreigziabher A.
1
OOP Concepts
2
4.1 Inheritance – Deriving a class
* Inheritance is the process by which one class object acquire or get the properties or
characteristics or functionality of another class object.
* In inheritance a class acquires or inherits the methods and variables of its super
classes.
* Super class is called Base/Parent class.
* Sub class is called derived/child class
* A subclass is a specialized version of a superclass and adds its own, unique elements.
4.1.1 Inheritance Basics
* To inherit a class use the extends keyword.
* To create a superclass called A and a subclass called B.
public class A {
//….
}
public class B extends A {
//….
}
* Each subclass inherits all variables and methods from the super class except private variables
and methods.
* Objects that are derived from other object "resemble" their parents by inheriting both
state (fields) and behavior (methods). 3
// A simple class hierarchy. class Shapes {
// A class for two-dimensional objects. public static void main(String args[]) {
class TwoDShape { //Define 2D Generic types[ Square, Triangle t1 = new Triangle(); //Create object t1
//Triangle, Rectangle…] Triangle t2 = new Triangle(); //Create object t2
double width; t1.width = 4.0; All members of Triangle are
double height;
t1.height = 4.0; available to Triangle
void showDim() { objects,
System.out.println("Width and height are " +width + "
t1.style = "isosceles"; even those inherited from
and " + height); t2.width = 8.0; TwoDShape
} t2.height = 12.0;
} t2.style = "right";
// A subclass of TwoDShape for triangles. System.out.println("Info for t1: ");
//Triangle inherits TwoDShape-creates specific2DShape type. t1.showStyle();
class Triangle extends TwoDShape { t1.showDim();
String style;
System.out.println("Area is " + t1.area());
double area() { // computes the area of triangle
//Triangle can refer to the members of TwoDShape as if System.out.println();
//they were part of Triangle. System.out.println("Info for t2: ");
return width * height / 2; t2.showStyle();
}
t2.showDim();
void showStyle() { // displays the triangle style. System.out.println("Area is " + t2.area());
System.out.println("Triangle is " + style); }
}} 4
}
void showStyle() {
//Private members of super class can be accessed System.out.println("Triangle is " + style);
through accessor methods in subclass. }}
// Use accessor methods to set and get private class Shapes2 {
members. public static void main(String args[]) {
// A class for two-dimensional objects. Triangle t1 = new Triangle();
class TwoDShape {
Triangle t2 = new Triangle();
private double width; // these are
private double height; // now private t1.setWidth(4.0);
// Accessor methods for width and height. t1.setHeight(4.0);
double getWidth() { return width; } t1.style = "isosceles";
double getHeight() { return height; } t2.setWidth(8.0);
void setWidth(double w) { width = w; } t2.setHeight(12.0);
void setHeight(double h) { height = h; } t2.style = "right";
void showDim() { System.out.println("Info for t1: ");
System.out.println("Width and height are " + t1.showStyle();
width + " and " + height);
t1.showDim();
}}
// A subclass of TwoDShape for triangles.
System.out.println("Area is " + t1.area());
class Triangle extends TwoDShape { System.out.println();
String style; System.out.println("Info for t2: ");
double area() { t2.showStyle();
return getWidth() * getHeight() / 2; t2.showDim();
} 5 System.out.println("Area is " + t2.area());
}}
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
public class Test Animal {
} public static void main(String[] args) {
} Animal a = new Animal();
class Cat extends Animal { Cat b = new Cat();
public void eat(String str) { Dog c = new Dog();
System.out.println("Drinking for milk"); Goat d = new Goat();
} a.eat("grass");
} b.eat("milk");
c.eat(“meat");
class Dog extends Animal {
d.eat("grass");
public void eat(String str) {
}}
System.out.println("Eating for meat"); Output
} Eating for grass
} Drinking for milk
class Goat extends Animal { Eating for meat
public void eat(String str) { Eating for leaf
System.out.println(“Eating for leaf"); * The class Animal is a superclass, whose method eat()
has been accessed by its sub classes Cat, Dog and Goat.
} The objects of the subclasses is then created in the main
} 6 class to test. Through the objects of these class, their
respective methods has been called.
public class Parent { //Super or Base class
public String abc=null;
public String xyz=null;
public void printOutput() {
System.out.println("Output of Inheritance :"+abc);
System.out.println("Output of Second Inheritance :"+xyz);
}}
public class Child extends Parent { //Derived/Subclass inherits Parent class
public void method() {
abc="This is inheritance java program";
xyz="This is child class where extends used";
printOutput();
}
public static void main(String[] args) {
Child c=new Child();
c.method();
}} Output of Inheritance :This is inheritance java program
7
Output of Second Inheritance :This is child class where extends used
class Add {
int a, b;
void getdata(int x, int y) { a=x; b=y; }
void sum() { System.out.println(”sum = “+(a+b)); }
}
class Add1 extends Add { //Add1 inherits from Add
int c, d;
void getdata() { c=20; d=30; }
void sum() { System.out.println(”sum = “+(c+d)); }
}
class AddTest {
public static void main(String args[]) {
Add add = new Add();
add.getdata(2,3);
add.sum(); //5
Add1 add1= new Add1();
add1.getdata();
add1.sum(); //50
} 8
}
• Inheritance is the mechanism by which code reusability is achieved. An object can inherit the variables
and methods of another object.
• The child class can use the methods and variables of the superclass and add to them its own methods and
variables.
public class Car {
protected double CarSpeed;
protected String CarModel;
private int ID=0; //Declare ID as private so that RaceCar can’t access it
public void setCarModel(String CarModel) { this.CarModel = CarModel; }
public void setCarSpeed(double CarSpeed) { this.CarSpeed = CarSpeed; }
public String getCarModel() { return CarModel; }
public int getCarSpeed() { return CarSpeed; }
}
class RaceCar extends Car{ //Child Class RaceCar uses the codes in Parent Class Car: Code Reusability!
public void RunTurbo() {
CarSpeed+=100;
}}
public class CarMain {
public static void main(String[] args) { // Main Method or Function
RaceCar rc=new RaceCar();
rc.setCarModel(“ABC”); rc.setCarSpeed(50); rc.getCarModel(); rc.getCarSpeed();
rc.RunTurbo(); rc.getCarSpeed();
} } //Any instance of RaceCar can use the members of Car class except the variable (int ID) because it is private.
9
* The mechanism by which subclass is derived from it's parent class is known as single inheritance.
class A {
int x;
int y;
int get(int p, int q) { x=p; y=q; return(0); }
void Show() {
System.out.println(x);
}
}
class B extends A { // Subclass B inherits the properties of Superclass A
void display(){
System.out.println(“Inside Inherited/Subclass B: “+y);
}
}
public class MainClass {
public static void main(String args[]){
A a = new A();
B b = new B();
a.get(5,6);
a.Show(); //5
b.display(); // Inside Inherited/Subclass B: 6
}
} 10
* When a subclass is derived from a derived class then this mechanism is known
as the multilevel inheritance.
class A {
int x;
int y;
int get(int p, int q) { x=p; y=q; return(0); }
void Show() { System.out.println(x); //5 }
}
class B extends A {
double sq; //Instance variable of Sub/Derived/Child Class B
void Show() { sq=math.pow(x,2); System.out.println("B: "+sq ); //25 }
}
class C extends B {
double sqrt; //Instance variable of Sub/Derived/Child Class C
void display() { sqrt=Math.sqrt(sq); System.out.println("C: “+sqrt); //5}
}
public class MultilevelInhe {
public static void main(String args[]) {
A a = new A(); B b = new B(); C c = new C();
a.get(5,6);
a.Show(); b.Show(); c.display(); 11
}}
* A subclass can also explicitly call a constructor of its immediate superclass. This is
done by using the super constructor call.
* A super constructor call in the constructor of a subclass will result in the execution
of relevant constructor from the superclass, based on the arguments passed.
public class Arithmetic {
double x;
double y;
Arithmetic(double x, double y) { this.x=x; this.y=y; } //Parameterized Constructor
}
public class Addition extends Arithmetic {
Addition(double x, double y) {
super(x,y); // Calls Super Class Constructor to initialize instance variables from
Addition subclass
}}
public class Multiplication extends Arithmetic {
double z; //Subclass Multiplication adds one instance variable
Multiplication(double x, double y, double z) {
super(x,y); // Calls Super Class Constructor to initialize instance variables
this.z=z;
}} 12
// Using super to overcome name hiding.
class A {
int i;
}
class B extends A { // Create a subclass by extending class A.
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i); // i in superclass: 1
System.out.println("i in subclass: " + i); // i in subclass: 2
}}
class UseSuper {
public static void main(String args[]) {
B b = new B(1, 2);
b.show();
}}
13
class Employee { class Typist extends Employee {
String ID; Typist(String id, String n,String a, double b) {
String name, address;
super(id, n, a); //Calls Superclass Constructor
final static double tx=10; //5% of tax
final static double pn=6; //6% of pension basic=b;
double salary; }
double basicvoid; Typist() { //Calls Typist Default Constructor
Employee() { ID=name=address="null";} super(); //Calls Super Class Default Constructor
Employee(String id, String n,String a) { basic=0; //set basic salary to 0
ID=id; name=n; address=a; }
} }
void computeSalary() {
//Compute Net Salary class EmployeeMainClass {
salary=basic-((basic*tx/100)+(basic* pn/100)); public static void main(String args[]) {
System.out.println("NET SALARY: “+salary); Manager m=new
} Manager("ASU/127/05","Abebe","Assosa",15000);
} Typist t=new Typist("ASU/130","Feven","Assosa",2000);
class Manager extends Employee{ System.out.println("MANAGER:");
Manager(int id, String n,String a, double b) { m.computeSalary(); // invoke/call method in Manager
super(id, n, a); //Calls superclass Constructor to System.out.println("TYPER:");
//initialize instance variables
basic=b; t.computeSalary(); //invoke/call method in Typist
} }
Manager() { super(); basic=0; } }
}
14
*Polymorphism is the ability to create variables and methods that
has more than one form.
*Polymorphism is the quality that allows one interface to access a
general class of actions.
15
5.3 Method Overloading and Overriding
5.3.1 Method Overloading
Method Overloading is defining two or more methods with the same name within
the same class.
However, Java has to be able to uniquely associate the invocation of a method
with its definition relying on the number and types of arguments.
Therefore the same-named methods must be distinguished:
1) by the number of arguments, or
2) by the types of arguments
Overloading and inheritance are two ways to implement polymorphism.
When java call an overloaded method, it simply executes the version of the method
whose parameters match the arguments.
Two methods are overloaded if the:
1. No of parameters are different
2. Type of parameters is different
16
3. Order of parameters is different
public void add(int i) { System.out.println(i+i); } //Has only one parameter
public void add(int i, int j) { System.out.println(i+j); } //Has two parameter
public void add(int i, int j, int k) { System.out.println(i+j+k); } //Has three parameter
17
public class Area {
public void computeArea(double base, double height) {
double area = (base* height)/2;
System.out.println(“The area of Triangle is: ”+area);
}
public void computeArea(int width, int length) {
double area = width*length;
System.out.println(“The area of Rectangle is: ”+area);
}
public void computeArea(double radius) {
double area = Math.PI*radius* radius;
System.out.println(“The area of Circle is: ”+area);
}}
public class AreaTest {
public static void main(String args[]) {
Area a = new Area();
a. computeArea(7.5,5);
a. computeArea(7,5);
a.computeArea(10); 18
}
* When a child class defines a method with the same name and signature as the parent,
then it is said that the child’s version overrides the parent’s version in his favor.
* When an overridden method is called from child class object, the version in the child
class is called not the parent class version.
* The return type, method name, number and type of the parameters of overridden
method in the child class must match with the method in the super class.
* You can call the super class variable & method from the child class with super
keyword.
super.variablename; and super.overriddenMethodName();
* Method overriding by subclasses with different number and type of parameters.
public class Findareas {
public static void main (String []agrs){
Figure f= new Figure(10 , 10); //Create object(Figure instance variable) f
Rectangle r= new Rectangle(9 , 5); //Create object(Rectangle instance variable) r
Figure figref; //Create object variable figref of Figure
figref=f; //figref holds reference of f
System.out.println("Area is :"+figref.area()); //Calls method area() in Figure
figref=r; //figref holds reference of r
System.out.println("Area is :"+figref.area()); //Calls method area() in Rectangle overrides area in Figure
}} 19
class Figure {
double dim1; double dim2;
Figure(double a , double b) {
dim1=a; dim2=b;
}
double area() {
System.out.println("Inside area for figure.");
return(dim1*dim2);
}}
class Rectangle extends Figure {
Rectangle(double a, double b) { super(a ,b); //Calls Super class constructor }
double area() { //Overrides the method in Super class
System.out.println("Inside area for rectangle.");
return(dim1*dim2);
}}
//The method area() in the subclass Rectangle overrides the method area() in
the surer class Figure
Result:
The above code sample will produce the following result.
Inside area for figure. Area is :100.0
Inside area for rectangle. Area is :45.0 20
// Method overriding.
class A {
int i, j;
A(int a, int b) { i = a; j = b; }
void show() { // display i and j
System.out.println("i and j: " + i + " " + j); }
}
class B extends A {
int k;
B(int a, int b, int c) { super(a, b); k = c; }
void show() { // display k – this overrides show() in A
System.out.println("k: " + k); //k: 3
}}
class Override {
public static void main(String args[]) {
B b = new B(1, 2, 3);
b.show(); // this calls show() in B which overrides/ignores it!
}
} 21
public class Employee {
Example of Polymorphism: Method Overriding!
private String name;
private double salary;
Employee(String n, double s) { name =n; salary=s; } //Constructor
public void setName(String nm) { name=nm; }
public String getName() {return name; }
public void setSalary(double s) { salary=s; }
public double getSalary() { return salary; }
}
class Manager extends Employee {
private double bonus;
Manager(String n, double s, double b) { super(n, s); bonus=b; }
public void setBonus(double b) { bonus=b; }
public double getBonus() { return bonus; }
public double getSalary() { // method overriding. Overrides the getSalary() in Employee Class
double basesalary = super.getSalary(); // calls getSalary() method in super class
return basesalary + bonus; // manager salary is salary+bonus;
}}
class EmployeeMainClass {
public static void main(String[]args) {
Employee e = new Employee("Programmer",20000);
System.out.println( e.getName()+ ": "+e.getSalary()); //Programmer: 20000.0
Manager m = new Manager("Boss",20000,5000);
e = new Manager("Boss",20000,5000); // e = m;
22
System.out.println( e.getName()+”: ”+e.getSalary()); //Boss: 25000.0
}}
* Encapsulation is a programming mechanism that binds together code and the
data it manipulates, and that keeps both safe from outside interference and
misuse.
* Encapsulation is the concept of hiding the implementation details of a class and
allowing access to the class through a public interface.
* It hides certain details and only show the essential features of the object.
* For this, we need to declare the instance variables of the class as private or protected
& access only the public methods rather than accessing the data(instance variable)
directly.
* We can prevent access to our object's data by declaring them as private & control
access to them.
* How encapsulation is achieved?
If you declare private variables in source code, it will achieve encapsulation
because it restricts access to that particular data. This statement is true in all
cases.
23
* In other words, encapsulation is the ability of an object to be a container (or capsule) for related
properties (i.e. data variables) and methods (i.e. functions).
public class Box {
private int length;
private int width;
private int height;
public Box(int len, int wid, int hei) { //Constructor
length=len; width=wid; height=hei;
}
public void setLength(int p) {length = p;} public int getLength() { return length;}
public void setWidth(int p) {width = p;} public int getWidth() { return width;}
public void setHeight(int p) {height = p;} public int getHeight() { return Height;}
public int displayVolume() {
System.out.println(getLength() * getWidth() * getHeight() ) ;
}
}
Public class MainBox {
public static void main(String args [ ]) {
Box b=new Box(3,4,5);
b.displayvolume(); //60
}}
24
* The ability to change the behavior of your code without changing your implementation
code is a key benefit of encapsulation.
* How to hide implementation details?
* Keep your class instance variables private or protected. But how could we access these
protected instance variables? Make our instance methods public and access private or
protected variables through public methods.
* For maintainability, flexibility, and extensibility
1.Keep instance variables protected (with an access modifier, often private).
2. Make public accessor methods, and force calling code to use those methods rather
than directly accessing the instance variable.
3. For the methods, use the Java naming convention of set and get.
public class Box {
private int size; // protect the instance variable. Only an instance of Box Class can access it
// Provide public getters and setters
public int getSize() { return size; }
public void setSize(int newSize) { size = newSize; }
}
class BoxMain {
public static void main(String args[]) {
Box b=new Box(); //create instance of Box
b.setSize(25); //access methods trough box objects
System.out.println("Size:"+b.getsize()); //Size: 25 25
}
* The internal portion (variables) of an object has more limited visibility than
the external portion (methods) which will protect the internal portion against
unwanted external access.
* //First step is to create the variables of the object private so that nobody can
access them from outside.
public class Employee {
private double salary; //
* //Second step is to provide public setters and getters methods for accessing
the private variables.
public void setSalary(double salary) {this.salary = salary; }
public double getSalary() { return salary; }
}
* //Third step is to create an object in main method and access the public
methods
public class MainClass {
public static void main(String[] args) {
Employee emp = new Employee ();
emp.setSalary(2000); //set Salary to 2000
emp.getSalary(); //2000 26
}}
public class Student {
private String ID;
private double cgpa;
public void setID(String ID) { this.ID = ID; }
public String getID() { return this.ID; }
public void setCGPA(double cgpa) {
if (cgpa < 0 && cgpa > 4) {
System.out.println("Invalid CGPA");
public class Employee { }
private double salary; //Privately Protect salary
public void setSalary(float salary) { else { this.cgpa = cgpa; }
if(salary<500 && salary>5000) { }
System.out.println(“Salary Must be >=500”);
}
public double getCGPA() { return this.cgpa; }
else { public static void main(String args[]) {
this.salary = salary; String ID = "ETR/350/04";
}
}
double cgpa = 3.25;
public float getSalary() { return salary; } Student stud = new Student();
} stud.setID(ID);
public class EmpMainClass {
public static void main(String args[]) { System.out.println(stud.getID());
double salary=2000; stud.setCGPA(cgpa);
Employee emp = new Employee(); System.out.println(stud.getCGPA());
emp.setSalary(salary);
emp.getSalary(); //2000 }
27
} }
}
class Check { class Login {
private double amount=0; private String password;
public int getAmount(){ public int getPassword(){
return amount; return password;
} }
public void setAmount(double amt){ public String setPassword(String pass){
amount=amt; password=pass;
} }
} }
public class Mainclass { public class Mainclass {
public static void main(String[] args){ public static void main(String[] args) {
double amt=0; String Pass=“”;
Check obj = new Check(); Check obj = new Check();
obj.setAmount(200); //set amount to 200 obj.setPassword(“123”);//set password to 123
amt = obj.getAmount(); pass = obj.getPassword();
System.out.println("Your current System.out.println("Your Password is:
amount is: "+amt); "+pass); //Your Password is: 123
// Your current amount is: 200 }
} }
}
28
• Let's suppose that you need a class that gets control on debits and credits in a
bank account. This is critical. Let's suppose that you declare as public the
attribute 'balance'. Now suppose that you or another programmer which is
using your class made a mistake in somewhere in the code and just before
saving changes to database he did something like:
nameObject.balance =someValue;
• In this way he has changed directly the balance of the account. That is wrong
because it must be changed just by using additions '+' and subtractions '-'
(credits and debits).
Using encapsulation we can help that:
class BankAccount {
private double balance;
private double init;
private double debit;
private double credit;
public BankAccount(double ini, double deb, double cre){
init = ini; debit = deb; credit = cre;
balance = init + credit - debit; //initialize the balance
} 29
public double getDebit() { return debit; }
//add to debit and sub from balance
public void setDebit(double debit) {
this.debit += debit;
balance -= debit;
}
public double getCredit() { return credit; }
//add to credit and add to balance
public void setCredit(double credit) {
this.credit += credit;
balance += credit;
}
public double getBalance() { return balance; }
public double getInit() { return init; }
}
public class BankAcct {
public static void main(String[] args) {
BankAccount bacct = new BankAccount (50,200,300);
System.out.println("Your Current Balance is: "+bacct.getBalance());
} 30
}
5.5 Abstract Classes
• An abstract class is a class that is partially implemented and whose purpose is solely
represent abstract concept.
• Abstract classes are made up of one or more abstract methods.
• Abstract classes cannot be instantiated because they represent abstract concept.
• When we do not want to allow any one to create object of our class, we define the class as
abstract.
• Contain fields that are not static and final as well as implemented methods
• public class Animal { } is an abstraction used in place of an actual animal
• Abstraction is nothing but data hiding. It involves with the dealing of essential information.
• Abstract classes are those that works only as the parent class or the base class. Subclasses
are derived to implement.
• Declared using abstract keyword
• An abstract method is a method which has no implementation (body).
• The body of this method is provided by a subclass of the class in which the abstract method
is declared.
• Abstract class can’t be instantiated(Object can’t be created), but can be extended to sub
classes
• Lets put common method name in one abstract class
• An abstract class can inter mix abstract and non abstract methods.
• Abstract class and method cannot be declared as final.
• Abstract method cannot be declared as static.31
• Abstract method cannot be declared as private.
//An Other Example of Abstract Classes
abstract class Shape {
abstract void draw();
}
class Rectangle extends Shape{
void draw() {
System.out.println(“Drawing Rectangle”);
}}
class Traingle extends Shape{
void draw(){
System.out.println(“Drawing Traingle”);
}}
class AbstractDemo {
public static void main(String args[]) {
Shape s1=new Rectangle();
s1.draw();
s1=new Traingle();
s1.draw();
}
}
Result:
Drawing Rectangle
Drawing Traingle
32
public class Triangle extends TwoDShape {
public abstract class TwoDShape {
private double width;
private String style;
private double height; // A default constructor.
private String name; Triangle() {
TwoDShape() {// A default constructor. super();
width = height = 0.0; style = "null";
name = "null"; }
} // Constructor for Triangle.
// Parameterized constructor.
TwoDShape(double w, double h, String n) {
Triangle(String s, double w, double h) {
width = w; super(w, h, "Triangle");
height = h; style = s;
name = n; }
}
// Accessor methods for width and height. // Construct an isosceles triangle.
double getWidth() { return width; }
double getHeight() { return height; }
void setWidth(double w) { width = w; }
double area() {
void setHeight(double h) { height = h; } return getWidth() * getHeight() / 2;
String getName() { return name; } }
void showDim() { void showStyle() {
System.out.println("Width and Height are " + System.out.println("Triangle is " + style);
width + " and " + height); }
} }
abstract double area(); // Now, area() is abstract.
} 33
public class Rectangle extends TwoDShape { public class AbstractMain {
Rectangle() { // A default constructor.
super(); //Calls Super Class Constructor public static void main(String[] args) {
} // TODO code application logic here
// Constructor for Rectangle. //Create objects of subclasses using the abstract class
Rectangle(double w, double h) {
super(w, h, "Rectangle"); TwoDShape t = new Triangle("Right", 8.0, 12.0);
} TwoDShape r = new Rectangle(10, 4);
34
• Abstraction is more like data hiding. You create a class with abstract methods. This
methods are the common for all objects which inherit from the abstract class but
every class implements these methods as they need. The main idea is that you can
declare an attribute of the an abstract class and this attribute can hold any object
that inherit from that abstract class. for example:
abstract class Car {
public abstract void ignition();
}
class Mazda extends Car {
public void ignition() { System.out.println("Code for starts Mazda engine");}
}
class Audi extends Car {
public void ignition() {
System.out.println("Code for starts Audi engine");
}}
public class Test {
public static void main(String[] args) {
Car car = new Mazda();
car.ignition();
car = new Audi ();
car.ignition(); 35
}}
abstract class Employee {
private String name;
private String address;
protected double salary;
public Employee(String name, String address, double salary) {
this.name = name;
this.address = address;
this.salary = salary;
}
public abstract double raise(); // abstract method
}
class Secretary extends Employee {
Secretary(String name, String address,double salary) {
super(name, address, salary); //Calls super class constructor to initialize data members
}
public double raise(){
return salary;
}
} 36
class Salesman extends Employee{
private double commission;
public Salesman(String name, String address, double salary, double commission) {
super(name, address, salary); //Calls super class constructor
this.commission=commission;
}
public double raise() {
salary = salary + commission;
return salary;
}
}
class Manager extends Employee {
Manager(String name, String address,double salary) {
super(name, address, salary); //Calls super class constructor
}
public double raise(){
salary = salary + salary * .05;
return salary;
} 37
}
class Worker extends Employee {
Worker(String name, String address, double salary) {
super(name, address, salary); //Calls Super Class Constructor
}
public double raise() {
salary = salary + salary * .02;
return salary;
}
}
public class Main {
public static void main(String[] args) {
Secretary a=new Secretary(“Abraham”,”Assosa”,1000);
Manager b=new Manager(“Worku”,”Assosa”,2000);
Worker c= new Worker(“Aster”,”Assosa”,1000);
Salesman d= new Salesman(“Daniel”,”Assosa”,1500,200);
Employee[] ArrayEmployee=new Employee[4];
ArrayEmployee[0]=a;
ArrayEmployee[1]=b;
ArrayEmployee[2]=c; Output
ArrayEmployee[3]=d; Final Salary: 1000.0
for(int i=0;i< ArrayEmployee.length; i++){ Final Salary: 2100.0
double s = ArrayEmployee[i].raise(); Final Salary: 1020.0
System.out.println(“Final Salary: “+s); Final Salary: 1700.0
}} 38
}