0 likes | 1 Vues
This is clear and easily understandable java PowerPoint/slides
E N D
Chapter Five OOP Concepts 1
4.1Inheritance – 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 "resemble" their parents by inheriting both state (fields) and behavior (methods). 2
class Shapes { public static void main(String args[]) { Triangle t1 = new Triangle(); //Create object t1 Triangle t2 = new Triangle(); //Create object t2 t1.width = 4.0; t1.height = 4.0; t1.style = "isosceles"; t2.width = 8.0; t2.height = 12.0; t2.style = "right"; System.out.println("Info for t1: "); t1.showStyle(); t1.showDim(); System.out.println("Area is " + t1.area()); System.out.println(); System.out.println("Info for t2: "); t2.showStyle(); t2.showDim(); System.out.println("Area is " + t2.area()); } } // A simple class hierarchy. class TwoDShape { //Define 2D Generic types double width; double height; void showDim() { System.out.println("Width and height are " +width + " and " + height); } } All members of Triangle are available to Triangle objects, even those inherited from TwoDShape // A subclass of TwoDShape for triangles. //Triangle inherits TwoDShape-creates specific2DShape type. class Triangle extends TwoDShape { String style; double area() { return width * height / 2; } void showStyle() { // displays the triangle style. System.out.println("Triangle is " + style); } } 3
void showStyle() { System.out.println("Triangle is " + style); }} class Shapes2 { public static void main(String args[]) { Triangle t1 = new Triangle(); Triangle t2 = new Triangle(); t1.setWidth(4.0); t1.setHeight(4.0); t1.style = "isosceles"; t2.setWidth(8.0); t2.setHeight(12.0); t2.style = "right"; System.out.println("Info for t1: "); t1.showStyle(); t1.showDim(); System.out.println("Area is " + t1.area()); System.out.println(); System.out.println("Info for t2: "); t2.showStyle(); t2.showDim(); System.out.println("Area is " + t2.area()); }} //Private members of super class can be accessed through accessor methods in subclass. // Use accessor methods to set and get private members. // A class for two-dimensional objects. class TwoDShape { private double width; // these are private double height; // now private // Accessor methods for width and height. double getWidth() { return width; } double getHeight() { return height; } void setWidth(double w) { width = w; } void setHeight(double h) { height = h; } void showDim() { System.out.println("Width and height are " + width + " and " + height); } } // A subclass of TwoDShape for triangles. class Triangle extends TwoDShape { String style; double area() { return getWidth() * getHeight() / 2; } 4
class Employee { String ID; String name, address; final static double tx=10; //5% of tax final static double pn=6; //6% of pension double salary; double basic; Employee() { ID=name=address="null";} Employee(String id, String n,String a) { ID=id; name=n; address=a; } void computeSalary() { //Compute Net Salary salary=basic-((basic*tx/100)+(basic* pn/100)); System.out.println("NET SALARY: “+salary); } } class Manager extends Employee{ Manager(int id, String n,String a, double b) { super(id, n, a); //Calls superclass Constructor to //initialize instance variables basic=b; } Manager() { super(); basic=0; } } class Typist extends Employee { Typist(String id, String n,String a, double b) { super(id, n, a); //Calls Superclass Constructor basic=b; } Typist() { //Calls Typist Default Constructor super(); //Calls Super Class Default Constructor basic=0; //set basic salary to 0 } } class EmployeeMainClass { public static void main(String args[]) { Manager m=new Manager("ASU/127/05","Abebe","Assosa",15000); Typist t=new Typist("ASU/130","Feven","Assosa",2000); System.out.println("MANAGER:"); m.computeSalary(); // invoke/call method in Manager System.out.println("TYPER:"); t.computeSalary(); //invoke/call method in Typist } } 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
1. No of parameters are 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
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. * 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; 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; System.out.println( e.getName()+”: ”+e.getSalary()); //Boss: 25000.0 }} Example of Polymorphism! 13
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 protected variables through public methods. 14
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 { private double salary; //Privately Protect salary public void setSalary(float salary) { if(salary<500 && salary>5000) { System.out.println(“Salary Must be >=500”); } else { this.salary = salary; } } public float getSalary() { return salary; } } 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"); } else { this.cgpa = cgpa; } } public double getCGPA() { return this.cgpa; } public static void main(String args[]) { String ID = "ETR/350/04"; double cgpa = 3.25; Student stud = new Student(); stud.setID(ID); System.out.println(stud.getID()); stud.setCGPA(cgpa); System.out.println(stud.getCGPA()); } public class EmpMainClass { public static void main(String args[]) { double salary=2000; Employee emp = new Employee(); emp.setSalary(salary); emp.getSalary(); //2000 } } 16 }
class Login { private String password; public int getPassword(){ return password; } public String setPassword(String pass){ password=pass; } } public class Mainclass { public static void main(String[] args) { String Pass=“”; Check obj = new Check(); obj.setPassword(“123”);//set password to 123 pass = obj.getPassword(); System.out.println("Your Password is: "+pass); //Your Password is: 123 } } class Check { private double amount=0; public int getAmount(){ return amount; } public void setAmount(double amt){ amount=amt; } } public class Mainclass { public static void main(String[] args){ double amt=0; Check obj = new Check(); obj.setAmount(200); //set amount to 200 amt = obj.getAmount(); System.out.println("Your current amount is: "+amt); // 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 } public double getDebit() { return debit; } 18
//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 { private String style; // A default constructor. Triangle() { super(); style = "null"; } // Constructor for Triangle. Triangle(String s, double w, double h) { super(w, h, "Triangle"); style = s; } public abstract class TwoDShape { private double width; private double height; private String name; TwoDShape() {// A default constructor. width = height = 0.0; name = "null"; } // Parameterized constructor. TwoDShape(double w, double h, String n) { width = w; height = h; name = n; } // Accessor methods for width and height. double getWidth() { return width; } double getHeight() { return height; } void setWidth(double w) { width = w; } void setHeight(double h) { height = h; } String getName() { return name; } void showDim() { System.out.println("Width and Height are " + width + " and " + height); } abstract double area(); // Now, area() is abstract. } // Construct an isosceles triangle. double area() { return getWidth() * getHeight() / 2; } void showStyle() { System.out.println("Triangle is " + style); } } 21
public class Rectangle extends TwoDShape { Rectangle() { // A default constructor. super(); //Calls Super Class Constructor } // Constructor for Rectangle. Rectangle(double w, double h) { super(w, h, "Rectangle"); } public class AbstractMain { public static void main(String[] args) { // TODO code application logic here //Create objects of subclasses using the abstract class TwoDShape t = new Triangle("Right", 8.0, 12.0); TwoDShape r = new Rectangle(10, 4); System.out.println("Object is " +t.getName()); System.out.println("Area is " + t.area()); System.out.println(); System.out.println("Object is " +r.getName()); System.out.println("Area is " + r.area()); System.out.println(); boolean isSquare() { if(getWidth() == getHeight()) { return true; } return false; } 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; ArrayEmployee[3]=d; for(int i=0;i< ArrayEmployee.length; i++){ double s = ArrayEmployee[i].raise(); System.out.println(“Final Salary: “+s); } } } Output Final Salary: 1000.0 Final Salary: 2100.0 Final Salary: 1020.0 Final Salary: 1700.0 25