PresentCh05 - OOP Concepts - Concise

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 24

OOP Concepts

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.

 Objects that are derived from other object


2 "resemble" their parents by

inheriting both state (fields) and behavior (methods).


class Shapes {
// A simple class hierarchy. public static void main(String args[]) {
class TwoDShape { //Define 2D Generic types Triangle t1 = new Triangle(); //Create object t1
double width; Triangle t2 = new Triangle(); //Create object t2
double height; t1.width = 4.0;
void showDim() { All members of Triangle are
t1.height = 4.0; available to Triangle objects,
System.out.println("Width and height are "
+width + " and " + height);
t1.style = "isosceles"; even those inherited from
TwoDShape
} t2.width = 8.0;
} 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 {
String style; t1.showDim();
double area() { System.out.println("Area is " + t1.area());
return width * height / 2; System.out.println();
} System.out.println("Info for t2: ");
void showStyle() { // displays the triangle style. t2.showStyle();
System.out.println("Triangle is " + style); t2.showDim();
} System.out.println("Area is " + t2.area());
} }
3
}
//Private members of super class can be accessed void showStyle() {
through accessor methods in subclass. System.out.println("Triangle is " + style);
// Use accessor methods to set and get private members. }}
// A class for two-dimensional objects. class Shapes2 {
class TwoDShape { public static void main(String args[]) {
private double width; // these are
Triangle t1 = new Triangle();
private double height; // now private
Triangle t2 = new Triangle();
// Accessor methods for width and height. t1.setWidth(4.0);
double getWidth() { return width; } t1.setHeight(4.0);
double getHeight() { return height; } t1.style = "isosceles";
void setWidth(double w) { width = w; } t2.setWidth(8.0);
void setHeight(double h) { height = h; } t2.setHeight(12.0);
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();
}
} System.out.println("Area is " + t1.area());
// A subclass of TwoDShape for triangles. System.out.println();
class Triangle extends TwoDShape { System.out.println("Info for t2: ");
String style; t2.showStyle();
double area() { t2.showDim();
return getWidth() * getHeight() / 2; 4 System.out.println("Area is " + t2.area());
} }}
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
basic=b;
final static double pn=6; //6% of pension
double salary; }
double basic; 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() { class EmployeeMainClass {
//Compute Net Salary public static void main(String args[]) {
salary=basic-((basic*tx/100)+(basic* pn/100));
System.out.println("NET SALARY: Manager m=new Manager("ASU/127/05","Abebe","Assosa",15000);
“+salary); Typist t=new Typist("ASU/130","Feven","Assosa",2000);
}
} System.out.println("MANAGER:");
class Manager extends Employee{ m.computeSalary(); // invoke/call method in Manager
Manager(int id, String n,String a, double b) {
super(id, n, a); //Calls superclass Constructor System.out.println("TYPER:");
to //initialize instance variables
t.computeSalary(); //invoke/call method in Typist
basic=b;
}
}
Manager() { super(); basic=0; } }
5
}
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.

Polymorphism – is achieved through


 1. Method Overloading -defining methods in same class with
different signatures(parameters, type).

 2. Method Overriding -defining methods in super and


subclasses with the same signature(parameter, type).

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.

 Two methods are overloaded if the:


1. No of parameters are different
2. Type of parameters is different
7
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

2. Type of parameters is different


public void add(int i, int j) { System.out.println(i+j); } //Has two integer type parameters
public void add(double i, double j) {System.out.println(i+j); } //Has two double type parameters
public void add(double i, int j) { System.out.println(i+j); } //Has one int & one double type parameters

3. Order of parameters is different


public void add(double i, int j) { System.out.println(i+j); } //Order is double and int
public void add(int i, double j) { System.out.println(i+j); } //Order is int and double

8
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.

* 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
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.

 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.

 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 public double getCGPA() { return this.cgpa;
salary; } }
}
public static void main(String args[]) {
String ID = "ETR/350/04";
public class EmpMainClass {
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.
•  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.
• Abstract method cannot be declared as private. 20
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.
} 21
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);

boolean isSquare() { System.out.println("Object is " +t.getName());


if(getWidth() == getHeight()) { System.out.println("Area is " + t.area());
return true; System.out.println();
} System.out.println("Object is " +r.getName());
return false; System.out.println("Area is " + r.area());
} System.out.println();
double area() {
return getWidth() * getHeight(); }
} }
}

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;
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
}} 25
}

You might also like