PresentCh05 - OOP Concepts - Concise
PresentCh05 - OOP Concepts - Concise
1
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.
▪ 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.
6
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
▪ When java call an overloaded method, it simply executes the version of the
method whose parameters match the arguments.
8
Example of Method Overloading
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); 9
}
* 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
}} 10
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 11
// 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!
}
} 12
public class Employee {
private String name; Example of Polymorphism!
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;
13
System.out.println( e.getName()+”: ”+e.getSalary()); //Boss: 25000.0
}}
▪ Encapsulation is a programming mechanism that binds together code and
the data it manipulates
▪ 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.
▪ 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 protected14variables through public methods.
▪ 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 15
}}
public class Employee { public class Student {
private double salary; //Privately Protect salary private String ID;
public void setSalary(float salary) { private double cgpa;
if(salary<500 && salary>5000) { public void setID(String ID) { this.ID = ID; }
System.out.println(“Salary Must be >=500”); public String getID() { return this.ID; }
} public void setCGPA(double cgpa) {
else { if (cgpa < 0 && cgpa > 4) {
System.out.println("Invalid CGPA");
this.salary = salary; }
} else { this.cgpa = cgpa; }
} }
public float getSalary() { return salary; public double getCGPA() { return this.cgpa;
} }
}
public static void main(String args[]) {
public class EmpMainClass { String ID = "ETR/350/04";
double cgpa = 3.25;
public static void main(String args[]) { Student stud = new Student();
double salary=2000; stud.setID(ID);
Employee emp = new Employee(); System.out.println(stud.getID());
emp.setSalary(salary); stud.setCGPA(cgpa);
emp.getSalary(); //2000 System.out.println(stud.getCGPA());
} }
16
} }
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 }
} }
}
17
• 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
} 18
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());
} 19
}
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. 20
22
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;
}
} 23
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;
} 24
}
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; Output
ArrayEmployee[2]=c;
Final Salary: 1000.0
ArrayEmployee[3]=d;
Final Salary: 2100.0
for(int i=0;i< ArrayEmployee.length; i++){
double s = ArrayEmployee[i].raise(); Final Salary: 1020.0
System.out.println(“Final Salary: “+s); Final Salary: 1700.0
25
}}
}