320 likes | 690 Views
Objects in Java. Object-Based Programming Outline. Introduction Implementing a Complex class Class scope Controlling Access to Members Initializing Class Objects: Constructors Using set & get Methods. Object-Based Programming Outline . Software Reusability final Instance Variables
E N D
Objects in Java Peter Cappello
Object-Based ProgrammingOutline • Introduction • Implementing a Complex class • Class scope • Controlling Access to Members • Initializing Class Objects: Constructors • Using set & get Methods
Object-Based ProgrammingOutline ... • Software Reusability • final Instance Variables • Composition: Objects as Instance Variables • Using the this reference • The finalize( ) method • Static Class Members
Introduction • When a problem is hard, we decompose it into littler problems, each of which is manageable. • Objects are 1 way of decomposing a program. • Goal: reduce the cost of creating & maintaining large programs.
Introduction ... • Object-oriented programming encapsulates: • data (attributes or instance variables) • methods (behaviors) into objects. • You interact with an object via its methods. • You do not [need to] know how the object is implemented.
Introduction ... • The set of methods through which you interact with an object is called its interface. • Generally, you are not allowed to change the internal state of an object directly (i.e., by changing its attribute values). • This is a custom, not a feature of Java.
Introduction ... • Decompose your program into programmer-defined types called classes • Each class is a generic description of a type of object (e.g., Color, Label). • Create particular elements (aka instantiating). These are objects. • Color is a class • Color.red is an object
Implementing a Complex class • Imagine that we want to create a new numeric type: a complex number. • Conceptually, it has 2 attributes: • the real part of the complex number • the imaginary part of the complex number • We use this to implement the Mandelbrot set program.
// Complex - implements a complex number public class Complex { private double real, // the real part imag; // the imaginary public Complex(double r, double i) { real = r; imag = i; } public Complex(Complex c) { real = c.getReal(); imag = c.getImag(); }
public double getReal() { return real; } public double getImag() { return imag; } public void add(Complex c) { real += c.getReal(); imag += c.getImag(); } public void multiply(Complex c) { double temp = real * c.getReal() - imag * c.getImag(); imag = real * c.getImag() + imag * c.getReal(); real = temp; } public double sizeSquared() { return real*real + imag*imag; } } // end Complex class
The class Complex • The keywords public & private are called member access modifiers. • private: only methods of the class can access it. • public: any method may access it. • Custom: make the class’s data private & methods public. • Constructor methods return no value.
Clients: Using the Complex class import java.awt.*; import java.applet.*; public class test1 extends Applet { public void paint(Graphics g) { Complex c = new Complex(1,0), d = new Complex(c), e = c; System.out.println("e.real = " + e.getReal() + ", d.real = " + d.getReal()); c.add(c); System.out.println("e.real = " + e.getReal() + ", d.real = " + d.getReal()); } } Output: e.real = 1.0, d.real = 1.0 e.real = 2.0, d.real = 1.0
Clients: Using the Complex class // compute the count associated with a complex point final private int getCount(Complex c, int lim) { Complex z = new Complex(c); int count = 1; for (; z.sizeSquared() < 4.0 && count < lim; count++) { z.multiply(z); z.add(c); } return count; }
The class Complex ... • When no identifier refers to an object, it is garbage. Complex c = new Complex(0,0); . . . c = new Complex(1,1); • Java’s garbage collector notes what objects are not being used (referenced), & collects their memory for reuse.
Class Scope • A class’s data & methods are within its class scope: • Such data & methods are directly accessible by all the class’s methods. public double getReal() { return real; }
Class Scope ... • Outside a class’s scope, public class members are accessible via a handle. • In the MandelbrotComplet class, we have: z.multiply(z); z.add(c); • We talk about hidden instance variables after we introduce the “this” reference.
Controlling Access to Members import java.applet.*; public class test1 extends Applet { public void paint(Graphics g) { Complex c = new Complex(0,0); c.real = 1; // compile error - real is private } } “Variable real in Complex not accessible from Complex” • Idea: • Clients only see interface • They do not see data or implementation of public methods.
Initializing Objects: Constructors • If you do not provide a constructor, Java provides a no-argument constructor. • Otherwise, Java provides no constructor. • The no-argument constructor initializes instance variables to their default values: • Numeric: 0 • boolean: false • Objects: null
public class Complex { private double real, // the real part of the complex number imag; // the imaginary part of the number public Complex(double r, double i) { real = r; imag = i; } public Complex(Complex c) { real = c.getReal(); imag = c.getImag(); } . . . • Constructors have no return type. • Their name is the class name. • Constructors typically are overloaded, as above.
Using set & get methods • Insist that clients examine the object’s state via its get methods. • Insist that clients modify the object’s state via its set methods • Allow the object to control “itself”. • Present its state in its own way • Modify its state in its own way.
Encapsulation as self-ownership • This notion of property rights for objects (“self-ownership”) prevents the chaos that is involuntary brain surgery: • Do not allow other objects to modify an object’s state without its consent.
Software Reusability • The goal is reuse • A means: the use of class libraries • Java class libraries are being created at a rapid rate. • Java programs then can be created from portable high quality classes with respect to their: • definition, design, implementation, test, documentation • The cost of quality is amortized over a large set of clients, increasing value.
Final Instance Variables • Defensive programming manifests itself by giving an entity no more privilege than it needs (e.g., need to know) • When a variable is a program constant (i.e., its value is set once in the program), we can specify this with the modifier final.
Final Instance Variables ... • When final is specified, the program: • must initialize it within the statement that declares it final • cannot modify after that • A compiler error results, if you do.
Final Instance Variables ... import java.applet.*; import java.awt.*; public class checkers extends Applet { public void paint( Graphics g ) { final int SIZE = 8, EDGE = 40, X = 10, Y = 10; g.fillRect(X, Y, SIZE*EDGE, SIZE*EDGE); // paint black square // paint red squares g.setColor(Color.red); for (int row = 0; row < SIZE; row++) for (int col = 0; col < SIZE; col += 2) // paint a row of red squares g.fillRect(X + (row % 2 + col)*EDGE, Y + row*EDGE, EDGE, EDGE); } }
Composition: Objects as Instance Variables • The most important use of objects is as instance variables of more complex objects. • Composition is referred to as a “has a” relation: • A car has an engine • An engine has a carburetor • A carburetor has a screw ...
Composition: Objects as Instance Variables • For example, we can define a class of Mandelbrot sets (see Lectures page) • Its instances are Mandelbrot sets. • A Mandelbrot set may be characterized by: • Complex LL - the complex point of its lower left corner • double edge - the length of its square region • int res - the resolution of its depiction • int lim - the iteration limit
Using the this reference • this refers to an object. • When an object refers to its own instance variables & methods, the use of this is implicit. • As an illustration, we can redefine Complex with explicit this references
Using the this reference ... • Another use of this is in the multiply method: • Instead of returning nothing (void), it now returns an object of type Complex: return this; // return myself! • See modified Mandelbrot usage, called concatenated (or cascaded or chained) method invocations. • The . operator associates left to right.
The finalize( ) method • Every class may have a special method called finalize, which returns no value. • finalize() is automatically invoked just before the object is collected by the garbage collector. • An example of this is given shortly.