Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
OBJECT ORIENTED PROGRAMMING Course 4 Loredana STANCIU [email protected] Room B613 INHERITANCE A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). Descendent — a class derived from other class INHERITANCE Every class has one and only one direct superclass (single inheritance). A subclass inherits all the members (fields, methods, and nested classes) from its superclass The constructor of the superclass is not inhereted but can be invoked from the subclass THE JAVA PLATFORM CLASS HIERARCHY Every class is implicitly a subclass of Object (java.lang package) Defines and implements behavior common to all classes Hierarchy of classes http://java.sun.com/javase/6/docs/api/java/ lang/Object.html THE JAVA PLATFORM CLASS HIERARCHY INHERITANCE - EXEMPLE class Polygon { protected double[ ] sides; public Polygon(int n) { sides = new double[n]; } public double perimeter( ) { double s=0; for(int i=0;i<sides.length;i++) s+=sides[i]; return s; } } INHERITANCE - EXEMPLE class Rectangle extends Polygon { public Rectangle(double L, double h){ super(4); sides[0] = sides[2] = L; sides[1] = sides[3] = h; } public double area( ){ return sides[0]*sides[1]; } } INHERITANCE - EXEMPLE class Client { public static void main (String [] args){ Rectangle r1 = new Rectangle (4, 2); System.out.println(“The perimeter is:” + r1.perimeter(); System.out.println(“The area is:” + r1.area(); } } SUBCLASSES Inherits all of the public and protected members of its parent, no matter what package the subclass is in In the same package as its parent, it inherits the package-private members of the parent The inherited fields and methods can be used directly Can declare a field in the subclass with the same name as the one in the superclass — hiding it SUBCLASSES Can have new fields and new methods Create a new instance method in the subclass that has the same signature as the one in the superclass — overriding Create a new static method in the subclass that has the same signature as the one in the superclass — hiding SUBCLASSES Does not inherit the private members of its parent class — accessed only if the superclass has public or protected methods Write a subclass constructor that invokes the constructor of the superclass CASTING OBJECTS Rectangle rt = new Rectangle(2,3); Rectangle Polygon Object rt is a Rectangle, a Polygon, and an Object Casting shows the use of an object of one type in place of another type (permitted by inheritance and implementations) Object obj = new Rectangle(2,3); implicit casting CASTING OBJECTS Rectangle rt = obj; compile-time error Rectangle rt = (Rectangle) obj; explicit casting the instanceof operator — a logical test to the type of a particular object if (obj instanceof Rectangle) {Rectangle rt = (Rectangle) obj; } OVERRIDING AND HIDING METHODS Instance Methods An instance method in a subclass with the same signature as an instance method in the superclass overrides the superclass's method. Allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed OVERRIDING AND HIDING METHODS Class Methods If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding: The version of the overridden method that gets invoked is the one in the subclass The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass OVERRIDING AND HIDING METHODS public class Animal { public static void testClassMethod() { System.out.println("The class method in Animal."); } public void testInstanceMethod() { System.out.println("The instance method in Animal."); } } OVERRIDING AND HIDING METHODS public class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat."); } public void testInstanceMethod() { System.out.println("The instance method in Cat."); } } OVERRIDING AND HIDING METHODS public class Client{ public static void main(String[ ] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); }} The output: The class method in Animal. -- hidden The instance method in Cat. -- overrided OVERRIDING AND HIDING METHODS Modifiers The access modifier for an overriding method can allow more, but not less, access than the overridden method Cannot change an instance method in the superclass to a class method in the subclass, and vice versa OVERRIDING AND OVERLOADING Override — a method having the same signature (name, plus the number and the type of its parameters) and return type into a subclass Overload — a method having the same name and return type but different list of parameters in the same class USING THE KEYWORD SUPER Used to invoke the superclass’s members public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); }} public class Subclass extends Superclass { public void printMethod(){ super.printMethod(); System.out.println("Printed in Subclass"); }} USING THE KEYWORD SUPER public class Client{ public static void main(String[] args) { Subclass s = new Subclass(); s.printMethod(); } } The output: Printed in Superclass. Printed in Subclass SUBCLASS CONSTRUCTORS public Rectangle(double L, double h){ super(4); sides[0] = sides[2] = L; sides[1] = sides[3] = h;} Invocation of a superclass constructor must be the first line in the subclass constructor. The syntax for calling a superclass constructor: super() or super(parameter list) PROBLEM Create a class to describe a company’s employees. The class should have a method to compute the salary based on the number of worked hours. Create a different class to describe the manager and override the salary method. SOLUTION public class Employee{ private String name, address; private double hour_wage; public Employee(String n, String a, double p){ name = n; address = a; hour_wage = p;} public double computeSal(int nr){ return (hour_wage*nr);} public void printData(int nr){ System.out.printf("%s worked %d hours and earned %f RON",name, nr, computeSal(nr));} } SOLUTION public class Manager extends Employee{ private double manag_all; public Manager(String n, String a, double p, double al){ super(n, a, p); manag_all = al;} public double computeSal(int nr){ return (1+ manag_all/100)*super.computeSal(nr));} } SOLUTION • public class Client{ – public static void main (String [] arg) throws IOException { • BufferedReader r_in = new BufferedReader(new InputStreamReader (System.in)); • • • • • • • Employee e1 = new Employee(“Al Bundy", "LA", 15.0); Employee e2 = new Manager(“Seifeld", "NY",20.0, 30.0); System.out.println(“How many hours? "); int h=Integer.parseInt(r_in.readLine()); e1.printData(h); e2.printData(h); r_in.close();} OBJECT AS A SUPERCLASS Every class is a descendant, direct or indirect protected Object clone() throws CloneNotSupportedException Creates and returns a copy of this object. public boolean equals(Object obj) Indicates whether some other object is "equal to" this one. OBJECT AS A SUPERCLASS protected Called by the garbage collector on an object public int hashCode() Returns a hash code value for the object. public final Class getClass() Returns the runtime class of an object. public void finalize() throws Throwable String toString() Returns a string representation of the object. OBJECT AS A SUPERCLASS Synchronizing the activities of independently running threads in a program public final void notify() public final void notifyAll() public final void wait() public final void wait(long timeout) public final void wait(long timeout, int nanos) THE CLONE() METHOD A class, or one of its superclasses, implements the Cloneable interface aCloneableObject.clone(); protected Object clone() throws CloneNotSupportedException public Object clone() throws CloneNotSupportedException Add implements Cloneable to your class's declaration THE EQUALS() METHOD Compares two objects for equality and returns true if they are equal public class Book { ... public boolean equals(Object obj) { if (obj instanceof Book) return ISBN.equals((Book)obj.getISBN()); else return false; } } THE EQUALS() METHOD Book firstBook = new Book("0201914670"); Book secondBook = new Book("0201914670"); if (firstBook.equals(secondBook)) System.out.println("objects are equal"); else System.out.println("objects are not equal"); The output: objects are equal THE FINALIZE() METHOD May be invoked on an object when it becomes garbage class MyClass{ private long a; public MyClass(long x){ a=x; System.out.println(“Object “ +a+ “ was created”);} protected void finalize() throws Throwable{ System.out.println(“Object “ +a+ “ was destroyed”);} } THE FINALIZE() METHOD class ClientClass{ public static void main (String [ ] args){ MyClass a; long no_obj = 50000; for( long i=4;i<no_obj;i++) { a=new MyClass(i); a=null;} } THE GETCLASS() METHOD You cannot override getClass() Returns a Class object, which has methods you can use to get information about the class: Its name (getSimpleName()) its superclass (getSuperclass()) the interfaces it implements (getInterfaces()) void printClassName(Object obj) { System.out.println("The object's class is “ + obj.getClass().getSimpleName()); } http://java.sun.com/javase/6/docs/api/java/lang/Class.html WRITING FINAL CLASSES AND METHODS Indicate that the method cannot be overridden by subclasses class ChessAlgorithm { enum ChessPlayer { WHITE, BLACK } ... final ChessPlayer getFirstPlayer() { return ChessPlayer.WHITE; } ...} An entire class final — when creating an immutable class like the String class ABSTRACT METHODS AND CLASSES An abstract class: a class that is declared abstract cannot be instantiated, but they can be inherited An abstract method — a method that is declared without an implementation abstract void moveTo(double deltaX, double deltaY); If a class includes abstract methods, the class itself must be declared abstract ABSTRACT METHODS AND CLASSES public abstract class GraphicObject { // declare fields // declare non-abstract methods abstract void draw(); } The subclass has to provide implementations for all of the abstract methods — abstract ABSTRACT METHODS AND CLASSES Graphic objects: states (for example: position, orientation, line color, fill color) behaviors (for example: moveTo, rotate, resize, draw) ABSTRACT METHODS AND CLASSES abstract class GraphicObject { int x, y; ... void moveTo(int newX, int newY) { ... } abstract void draw(); abstract void resize(); } ABSTRACT METHODS AND CLASSES class Circle extends GraphicObject { void draw() { ... } void resize() { ... } } class Rectangle extends GraphicObject { void draw() { ... } void resize() { ... } } WHAT IS POLYMORPHISM? The ability of one object to be treated, or used, like another A powerful tool allowing architectures to be: designed and built that will be flexible enough to change with businesses' needs, stable enough not to require redesign and rebuild on a regular basis OVERLOADING (PARAMETRIC) POLYMORPHISM A class or classes implement methods that are the same in signature except for the parameters passed to the method One class can handle many different types of arguments to a specific method public void draw(int i){…} public void draw(double d){…} public void draw(char c){…} OVERRIDING POLYMORPHISM Occurs when a child class overrides the method implementation of the parent class Different child classes have different behaviors based on some intrinsic characteristic of the child class public class Drink{ … public void ingest() {…} } OVERRIDING POLYMORPHISM public class Milk extends Drink{ … public void ingest() {//action specific} } public class Vodka extends Drink{ … public void ingest() {//action specific} } INCLUSION POLYMORPHISM A child class inherits its method substance from the base or parent class Enables objects or systems that would previously have used the base class to use the child classes with equivalent results COERCION POLYMORPHISM A primitive or object type is cast or "coerced" into being another primitive type or object type Rectangle rt = (Rectangle) obj; float f = 3.4; int I = (int) f; PROBLEM Create an abstract class to describe a bank account. There can be only two types: RON and EUR accounts. One can make the following operations: depose, extract, and transfer money between two accounts of the same type. An owner will receive an interest which computes as follows: 0.03 of deposit for EUR account 0.06 of deposit for RON account Override equals() and toString() methods. SOLUTION public abstract class Account{ private double sum; public Account(double s){ sum = s;} public void depose(double s){ sum+=s;} public void extract(double s){ sum-=s;} public double getSum(){ return sum;} ………………………………………………………………………… SOLUTION ……………………………………………………………………… abstract public double interest(); abstract public void transfer(Account a, double s); public boolean equals(Account a) { if (sum==a.sum) return true; else return false;} public String toString(){ return String.format("The account's sum is %6.2f",sum);} } SOLUTION public class RonAcc extends Account{ public RonAcc(double s){ super(s);} public double interest(){ return 0.05*getSum();} public void totalAmount(){ depose(interest());} public void transfer(Account a, double s){ if(a instanceof RonAcc) {this.extract(s); a.depose(s);} else System.out.println("Account mismatch");} } SOLUTION public class EurAcc extends Account{ public EurAcc(double s){ super(s);} public double interest(){ return 0.03*getSum();} public void totalAmount(){ depose(interest());} public void transfer(Account a, double s){ if(a instanceof EurAcc) {this.extract(s); a.depose(s);} else System.out.println("Account mismatch");} } SOLUTION import java.io.*; public class ClientAcc{ public static void main (String [] arg) throws IOException { BufferedReader r_in = new BufferedReader(new InputStreamReader (System.in)); System.out.println("How much money is in Ron account?"); Account a1 = new RonAcc(Double.parseDouble(r_in.readLine())); System.out.println("How much money is in EUR account?"); Account a2 = new EURAcc(Double.parseDouble(r_in.readLine())); ………………………………………………………………… SOLUTION ………………………………………………………………………… ((RonAcc) a1).totalAmount(); System.out.println(a1); ((EURAcc) a2).totalAmount(); System.out.println(a2); ((RonAcc) a1).transfer(a2,10.2); r_in.close();} } REFERENCES The Java Tutorials. Learning the Java Language. http://java.sun.com/docs/books/tutorial/java/IandI /subclasses.html The Power of Polymorphism, http://www2.syscon.com/itsg/virtualcd/java/archives/0508/barnab ee/index.html