1 / 42

Chapter 3

Chapter 3. Object Oriented Programming in Java. Classes & Object Bank Account Example ADT Inheritance Overloading Interfaces Packages. Classes & Objects. Fields are data variables associated with a class or with instances of the class primitive data (int, double, …)

dasan
Télécharger la présentation

Chapter 3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3 Object Oriented Programming in Java • Classes & Object • Bank Account Example • ADT • Inheritance • Overloading • Interfaces • Packages

  2. Classes & Objects • Fields are data variables associated with a class or with instances of the class • primitive data (int, double, …) • object data ( BigInteger r ) • Methods provide execution behavior and operate on the data fields • Classes and Interfaces can be members of other Classes or Interfaces.

  3. Creating Objects • Objects are primitive or user defined. • Primitive objects are by value, user defined objects are references. • User defined Objects are created with constructors and the “new” keyword. Point center = new Point(4.0,5.9); • Compiler provides a default constructor.

  4. Constructor • A call to new C() generates a new C-object. • The object is initialised by calling the constructor method C() in class C. • The result is a reference to a new object of class C. • Constructor method for a given class can be overloaded, but must use distinct parameter lists.

  5. Destructor ? • Formal Destructors not part of language but exist in two ways: • finally blocks may follow try blocks to clean up regardless of how a try block is exited (exception or normally) • finalize() methods invoked by the garbage collector thread. • When there are no active references to an object storage is automatically reclamed by a garbage collector thread running in the background.

  6. Methods and Parameters • methods operate on the data fields of a class. • methods have zero or more parameters and may return values or be void. • a methods name, number of parameters and their type make up the signature of the method. • two methods may share a name if they have different signatures.

  7. Storage and Methods • storage should be private • methods “look” inline, but there is nothing meaningful about “inline” for uncompiled languages class ASimpleClass { int aVariable; // field boolean aMethod() { // method if (aVariable==0) { aVariable++; return true; } else { return false; } } ASimpleClass(){aVariable = 0;}//constructor } • Note there is nothing about visibility (yet)

  8. Static Fields • static fields in a class or interface belong to the class. If there are instances of a class with static data fields then all instances share the static data fields • static methods are invoked using the class name.

  9. Invoking a Method • a non-static method is invoked using an object of the class and the “dot” operator. • Point p = new Point(3.2,3.3);p.clear(); • the object on which the method is invoked is the “receiver”. The method is a “message” to the object.

  10. this • the keyword “this” refers to the current receiving object. public void clear() {this.x = 0.0;y = 0.0; // this is assumed }

  11. Bank Account Example class BankAccount { protected int balance; public int withdraw(int amount) { if (balance > = amount) balance = balance-amount; return balance; } public int deposit(int amount) { balance = balance+amount; return balance; } BankAccount (int amount) { balance = amount; } BankAccount () { balance = 0; } }

  12. Abstract Data Type • Procedure abstraction is achieved by: • treating function as black box • Data abstraction is based on two key techniques • Data Encapsulation - keeping data and operations together in one location • Information Hiding - restricting visibility of implementation details to where needed. function as black box • Why Information Hiding? • Help manage software complexity • Isolate dependencies for easier Software Maintenance

  13. Complex Class • Information can be hidden by private qualifier for both data and methods. class Complex { private float re; private float im; public void add(Complex a){re=re+a.re;im=im+a.re;} public void mult(Complex a) { ...;} Complex (float r, float i) { re = r; im =i; } } • Can use as follows: Complex z = new Complex(1.0,2.0);//z = (1.0,2.0) z.add(new Complex(3.0,2.0));//z = z+(3.0,2.0) z.mult(new Complex(2.0,1.0));// z = z*(2.0,1.0)

  14. Changing the Complex Class unchanged interface class Complex { private float radius; private float angle; public void add(Complex a ) { .. .; } public void mult(Complex a) {...;} Complex (float r, float i) { .. } public static Complex makePolar(float rad, float ang) { Complex t = new Complex(); t.radius = rad; t.angle = ang; return t; } } new implementation new constructor

  15. Polymorphisms in Java • Polymorphism means “many shapes” in Greek. In programming languages,they refer to the ability of code to be versatile/generic/reusable. • Three types of polymorphisms in Java are: • Overloading (ad-hoc) • Overriding/Subtyping (class) • Genericity via topmost Object & TypeCasting (parametric)

  16. Inheritance • Classes may extend other classes. • variables of a subclass with the same name as those of a superclass shadow the superclass storage. • a method of a subclass with the same signature as that of a superclass overrides the superclass method. • objects of a subclass may be used in superclass variables. • Classes may extend only one class. If a class does not extend a class by default it extends the class Object.

  17. Inheritance • the keywordsuperrefers to the superclass. • super() is an ancestor constructor call from within a class • as in C++ • variables are shadowed • unlike C++ • methods are polymorphically bound by default (that is, every method is virtual) • overridden methods may be invoked assuper.method()

  18. Inheritance • General form : class X extends Superclass • No multiple inheritance. • Every class (except : java.lang.Object) has exactly one superclass. • If no extends clause is given, then Object is assumed. • Extension has two effects: • It creates a subtype • It includes all declarations of the extended class (superclass) in the extending class (subclass), unless they are overriden.

  19. Method Overriding • An extending class inherits all fields and methods of the class it extends. • It may redefine some inherited methods - this process is called overriding. class Base { print(Object x) { System.out.println(x); } } class Sub extends Base { PrintStream log = … ; print(Object x){log.println(x);} } • What is the effect of? Base x = new Sub(0); x.print(“hello”);

  20. Inherit the Bank Account class CurrentAcct extends BankAccount { private int overdraft; public void SetOD(int amt) {overdraft = amt } public int withdraw(int amount) { if (balance+overdraft > = amount) balance = balance-amount; return balance; } CurrentAcct(int amt, int d) {super(amt); overdraft = d; } CurrentAcct(){super(0);overdraft =0;} }

  21. Using Static fields/methods class SavingAcct extends BankAccount { protected static float interest; public static SetInterest(float amt) {interest = amt }; public int AddInterest() { balance=balance+((balance*interest)/365); return balance; } SavingAcct (int amt) { super(amt); } SavingAcct () { super(0); } } • Note that static methods cannot access non-static class members

  22. Final Class/Method/Object • Variables declared final cannot be modified, and must be initialized • during declaration: final int luckynumber = 8; • A method that is final cannot be overriden in a sub-class. This means that the function is statically bound and can be inlined. • A class that is declared final cannot be s superclass. That is they cannot be inherited.

  23. Abstract Method/Class • Objects of some classes, known as abstract classes, are not meant to be instantiated. • Each such abstract class contains one or more abstract (uninstantiated) methods. abstract class shape { private Point center; abstract void draw () { }; } • Even though a class is abstract, it may still contain instance data and non-abstract methods

  24. Subtyping • If class X extends class Y. X is said to be a subclass of Y. • By subtyping principle, an instance of X can be used wherever an instance of class Y is expected. • Because of subclassing, the static (declared) type of a variable might differ from the dynamic type of the runtime value it contains. • The dynamic type should be a subtype of the static type. • class X extends Y { … } • X anX; • Y anY; • aY = anX; // OK • anX = (X)aY; // explicit type conversion needed

  25. Procedure vs Subtyping • Programming with procedures draw (shape[] f) { for (i=0; i<=f.length; i++) { switch (f[i].kind) { case line: drawline(f[i]); break; case rectangle: drawrect(f[i]); break; case circle: drawcircle(f[i]); break; default: println (“Error “); } } } • Problem - Need to change this procedure whenever a new shape is added

  26. SubTypes • Programming with Subtypes : draw (shape[] f) { for (i=0; i<=f.length; i++) { f[i].draw() } } • Each shape can have its own draw procedure. • Add new shape & procedure together as an encapsulated unit. • Subtype Principle : • An object of a subtype can appear wherever an object of a supertype is expected.

  27. Typecasts & Typetests • A type conversion (C) expr checks whether the dynamic type of expr is (a subtype of) class C. If not, a ClassCastException is raised (see Exception topic later). • A type test expr instanceof C checks if the dynamic type of expr is (a subtype of) class C.

  28. Typecasts & Typetests Example: class String { … boolean equals(Object other) { if (other instanceof String) { String that = (String) other; if (this.len != that.len) return false; for (int i=0; i<this.len; i++) { if (this.charAt[i] != that.charAt[i]) return false; return true; } return false; }

  29. Overloading • It is possible to use the same method name with different argument lists. void print (String x) { … } void print (Exception x) { … } void print (int x) { … } void print (int x, int precision) { … } • Here, argument types will determine which method to use. • Unlike overriding, overloading uses the static types of argument.

  30. Generic Codes in Java ? • Consider: class Pair { int x; int y; Pair (int a, int b) {x = a;y = b;} void swap() { int temp; temp = x; x = y; y = temp; } } • Need to duplicate code if we have to deal with char, arrays, etc.

  31. Answer : Objects Class class Pair { Object x; Object y; Pair (Object a, Object b) {x = a; y = b; } void swap(){ Object temp; temp = x; x = y; y = temp; } } • Possible use: p = new Pair (new Integer(3),new Integer(5)); p.swap(); • Potential Problem: Pair (new Integer(3), “IC102S”);

  32. Interfaces • Interfaces specify operations to be supported without implementing them. • Components of interfaces: • methods • constants • Unlike classes, no method implementation, nor variables.

  33. Interfaces • For example, can treat storage devices such as memory, tapes, disk through the following interface: interface Storable { int READ =0; int WRITE = 1; byte[] get(); put(byte[] data); int lastOp(); // returns READ or WRITE; } Write Only

  34. Interfaces • Interfaces define the methods that may be used but do not specify instance storage. interface ConstAccount { double getBalance(); } class Account implements ConstAccount { double d_ = 0.0; void setBalance(double d) {d_ = d;} double getBalance() { return d_;} }

  35. Interafces • All methods in an interface are implicitly public and abstract. • All constants are implicitly public, static, final. • Interface can inherit from several other interfaces. • The following is a convenient hack for accessing constants without the class qualifier. • interface Colors { • int Red =0; • int Green = 1; • int Blue = 2; • } • class C implements Colors ...

  36. Multiple Ineritance (?) • One primary motivation for interface is to provide functionality of multiple inheritance, without the problem of name-clashes. • Both FlyingMachine and FloatingVessel may have the navigate() methods, resulting in a name-clash. • Interface can avoid this problem. class FlyingMachine class FloatingVessel class Seaplane

  37. Solution by Interface interface FloatingVessel { int navigate(Point f,Point t); void dropAnchor(); void liftAnchor(); } interface FlyingMachine { int navigate(Point f,Point t); void land(); void takeoff(double fuel); } class Helicopter implements FlyingMachine { int navigate(Point f,Point t){ … }; void land() { … }; void takeoff(double fuel) { … }; void hover() { … }; } class Seaplane implements FloatingVessel,FlyingMachine { int navigate(Point f,Point t) { … }; void land() { … }; void takeoff(double fuel) { … }; void dropAnchor() { … }; void liftAnchor() { … }; }

  38. Interfaces vs Abstract Classes abstract class X { public abstract int foo() { } } public interface X { public int foo(); }

  39. Packages • packages are Java’s way to manage name spaces. • Packages are implemented as directories within a file system. When package names must span systems, the common practice is to reverse the internet domain name import COM.Sun.games; • import is not inclusion and is only for the compiler. Class paths are used to find the class information at run time.

  40. Packages • Classes are organized into packages. • Most implementation let packages correspond to file directories • A packages clause: package myGroup.myPackage • at the beginning of a .java file declares all classes in the file to be members of that package

  41. Import/Scope Rules • Tedious to use fully qualified name all the time. Can use import clause to allows short names. import java.io.File import java.io.* • Scope rules • all variables need to be declared • local variables visible from point of declaration until end of block • class fields and methods visible everywhere in class let you useFileinstead ofjava.io.File makes available all files in java.ioin the unqualified form.

  42. Modifiers (summary) public - visible everywhere protected - visible in all subclasses & in same package package(default)- visible in same package private - visible only in same class. static - once per class, rather than perobject final - methods cannot beoverridden, fields cannot be reassigned abstract - methods : implementationdeferred synchronized - methods : for concurrency native - methods : non-Java code volatile - fields : might change from outside program

More Related