The complete Circle class public class Circle public
The complete Circle class public class Circle { public double x, y; // center coordinates public double r; // radius // the methods public double circumference() { return 2*3. 14*r; } public double area() { return 3. 14*r*r; } } 1
Using the Circle class public class Test. Circle { public static void main(String args[]) { Circle c; c = new Circle(); c. x = 2. 0; c. y = 2. 0; c. r = 5. 5; System. out. println(c. area()); } } 2
The this keyword zthis refers to the current object z. In the Circle class, the following definitions for area() are equivalent: public double area() { return 3. 14 * r; } public double area() { return 3. 14 * this. r; } z. Using the keyword clarifies that you are referring to a variable inside an object 3
Constructors z. A constructor is a special type of method Õhas the same name as the class z. It is called when an object is created Õnew Circle(); // “calls” the Circle() method z. If no constructor is defined, a default constructor that does nothing is implemented 4
A constructor for the Circle class public class Circle { public double x, y; // center coordinates public double r; // radius public Circle() { // sets default values for x, y, and r this. x = 0. 0; this. y = 0. 0; this. r = 1. 0; }. . . } 5
A constructor with parameters public class Circle { … public Circle(double x, double y, double z) { this. x = x; this. y = y; this. r = z; // using this is now a necessity }. . . } 6
Using the different constructors Circle c, d; c = new Circle(); // radius of circle has been set to 1. 0 System. out. println(c. area()); d = new Circle(1. 0, 5. 0); // radius of circle has been set to 5. 0 System. out. println(d. area()); 7
Method Overloading z. In Java, it is possible to have several method definitions under the same name Õbut the signatures should be different z. Signature: Õthe name of the method Õthe number of parameters Õthe types of the parameters 8
Syntax Summary z. Constructor without a parameter public classname() { *body of the constructor } 9
Syntax Summary z Overloading constructors public classname(type variablename) { *body of constructor } public classname( type variable-name, type variable-name) { *body of constructor } 10
Encapsulation z. A key OO concept: “Information Hiding” z. Key points ÕThe user of an object should have access only to those methods (or data) that are essential ÕUnnecessary implementation details should be hidden from the user ÕIn Java, use public and private 11
Access Modifiers zpublic Õa public variable/method is available for use outside the class it is defined in zprivate Õa private variable/method may be used only within the class it is defined in 12
The Circle class Revisited public class Circle { private double x, y; // center coordinates private double r; // radius //. . . } // when using the Circle class. . . Circle c; c. r = 1. 0; // this statement is not allowed 13
Outside access to private data z. No direct access z. Define (public) set and get methods instead or initialize the data through constructors z. Why? ÕIf you change your mind about the names and even the types of these private data, the code using the class need not be changed 14
Set and Get Methods z. Variables/attributes in a class are often not declared public z. Instead: Õdefine use a (public) set method to assign a value to a variable Õdefine a get method to retrieve that value z. Consistent with encapsulation 15
Set and Get Methods for Radius public class Circle { //. . . private double r; // radius // … public void set. Radius(double r) { this. r = r; } public double get. Radius() { return this. r; } //. . . } 16
Inheritance 17
Subclasses and Inheritance z. Inheritance: Õprogramming language feature that allows for the implicit definition of variables/methods for a class through an existing class z. In Java, use the extends keyword public class B extends A { … } Õobjects of subclass B now have access* to variables and methods defined in A 18
The Enhanced. Circle class public class Enhanced. Circle extends Circle { // as if area(), circumference(), set. Radius() and get. Radius() // automatically defined; x, y, r are also present (but are private // to the Circle class) private int color; public void set. Color(int c) { color = c; } public void draw() { … } public double diameter() { return get. Radius()*2; } } 19
Using a Subclass Enhanced. Circle c; c = new Enhanced. Circle(); // Circle() constructor // implicitly invoked c. set. Color(5); c. set. Radius(6. 6); System. out. println(c. area()); System. out. println(c. diameter()); c. draw(); 20
Applets and Inheritance z. Java Applets that we write extend the Applet class (defined in package java. applet) z. Methods such as add() (for adding visual components) are actually methods available in the Applet class zinit(), action(), and paint() are also available but can be overridden 21
Class Hierarchy z. Subclass relationship forms a hierarchy z. Example: Text. Field class ÕText. Field extends Text. Component which extends Object ÕObject is the topmost class in Java z. Exercise (use javap): Õdetermine where the methods set. Text(), get. Text(), hide(), and show() are defined 22
Method Overriding z. A method (with a given signature) may be overridden in a subclass z. Suppose class B extends A Õlet void operate() be a method defined in A Õvoid operate() may be defined in B Õobjects of class A use A’s operate() Õobjects of class B use B’s operate() 23
Dynamic Binding z. Let A be a superclass of subclasses B and C z. A variable of class A may refer to instances of A, B, and C z. Java facilitates the calling of the appropriate method at run time z. Example ÕA v; … v. operate(); 24
Constructors and Superclasses z. Suppose B extends A Õnew B() calls B’s constructor Õhow about A’s constructor ? z. Rule Õthe constructor of a superclass is always invoked before the statements in the subclass’ constructor are executed 25
super() z. Used to call a superclass’ constructor z. Implicitly included when not indicated If B extends A, the following are equivalent: public B() { // body of constructor } public B() { super(); // body of constructor } 26
Calling a particular Constructor z. Use super with parameters if a particular constructor should be called z. Example: public class Blue. Button extends Button { public Blue. Button(String s) { super(s); // without this, super() is called (label-less) set. Background(Color. blue); }… } 27
Default Constructors z. When no constructors are defined Õa default constructor with no parameters is implicitly included z. If at least one constructor is defined, with or without parameters Õa default constructor will not apply 28
Syntax Summary z. Extends and Super public class subclass extends superclass { public subclassconstructor(. . . ) { super(. . . ); *body of constructor }. . . } 29
Abstract Classes and Interfaces 30
“Incomplete” Classes z. Objects vs “concepts” z. Example: Circle and Shape Õcircles are shapes (Circle extends Shape) Õshapes (such as circle) have area and circumference Õhow area() and circumference() defined at the level of Shape? z. Shape has incomplete definitions 31
The Shape class z. One option Õmake area() and circumference() methods that do nothing (perhaps return 0. 0) ÕCircle could extend shape and then override these methods Õproblems ? z. Another option available in Java Õabstract class 32
Abstract Class z. Same as class Õbut it is possible to omit method bodies Õsyntax: xabstract before class (and method headers) xsemicolon at the end of the method headers z. Rules Õmay declare variables of abstract classes Õinstantiation not possible (new will not work) Õsubclasses must override incomplete methods 33
The Shape class public abstract class Shape { private int color; public void set. Color(int c) { color = c; } public abstract double circumference(); public abstract double area(); } 34
The Circle class public class Circle extends Shape { private double r; … // the compiler will complain if the ff methods are not defined public double circumference() { return 2*3. 14*r; } public double area() { return 3. 14*r*r; } } 35
Using Shape and Circle c; Shape s; c = new Circle(); // ok s = new Shape(); // not allowed -- Shape is abstract s = new Circle(); // ok because Circle is a // subclass of Shape 36
Another Example: Function Plotter z. Define an abstract class Function. Plotter that plots a mathematical function f() Õa method plot() plots a function f() by evaluating f() on some x values Õmake f() an abstract method, i. e. , public abstract double f(double x); z. Next, define classes that extend Function. Plotter and complete the definition of f() 37
Function Plotter, continued z. Line. Plotter defines f() as follows: public double f(double x) { return x; } z. Square. Plotter defines f() as follows: public double f(double x) { return x*x; } Note: Line. Plotter, Square. Plotter (and Circle, in the previous example) are called concrete classes 38
Why Use Abstract Classes? z. More robust code Õno need to use “new” on anything it shouldn’t be used on z. Enforces discipline ÕAbstract classes cannot be instantiated; they are meant to be extended ÕAnyone who extends an abstract class is now forced to define the incomplete parts 39
Interface z. None of the methods have bodies z. Instance variables not allowed z. Syntax Õinterface not class Õno need to put abstract before method headers Õimplements not extends on the complete (concrete) class 40
Rules on Interfaces z. May declare variables whose type is an interface Õobjects that are instances of classes that implement the interface may be referred to by such variables z. Instantiation not possible z. Implementing class must define all methods 41
Example public interface Switch { public void turn. On(); public void turn. Off(); public boolean is. On(); } public class Computer implements Switch { // must define turn. On(), turn. Off(), and is. On() in this class . . . } 42
Notes on Interfaces z. Interface variables can be declared Õe. g. , Switch s; z. Interfaces cannot be instantiated z. Interface variables may refer to objects of classes that implement the interface Õe. g. , s = new Computer(); z. A class may implement several interfaces 43
Multiple Inheritance z. Other OO languages such as C++ allow several superclasses for a given class Õnot possible in Java z. Implementation problems Õcommon members in superclasses z. In Java Õuse interfaces Õit is possible to implement several interfaces with no “conflicts” 44
Anonymous Classes z. Feature available in JDK 1. 1 or higher versions of Java z. Useful when ÕOnly one object of the concrete class needs to be created ÕIt is not too important to have a name for the concrete class 45
Back to Function. Plotter Example z. Without anonymous classes, the Line. Plotter class would look like this public class Line. Plotter extends Function. Plotter { public double f(double x) { return x; } } z. And then, in some main program … Line. Plotter lp = new Line. Plotter(); lp. plot(); 46
Using Anonymous Classes Function. Plotter lp = new Function. Plotter() { public double f(double x) { return x; } } lp. plot(); // no need to explicitly define a Line. Plotter class 47
Syntax Summary z. Anonymous classes abstractclassorinterface var = new abstractclassorinterface() { // complete the definitions of abstract // methods here } 48
The Java Event Models 49
Event-Driven Programming in Java z. Specifying actions for events performed on the GUI Õmost common example: clicking on a button z. The Java Event Models ÕJDK 1. 0. 2 (deprecated) ÕJDK 1. 1 and the new event model 50
Sample Applet: Hide. And. Show z. Visual objects Õtext field with some text Õtwo buttons z. Actions performed Õhide button causes text field to disappear Õshow button makes text field reappear 51
JDK 1. 0. 2 z. What needs to be done Õinit() method: create visual components and add them to the applet Õaction(): determine which button was clicked and indicate associated action z. Problems Õnested if-statement in action() inefficient Õcode associated with visual object far from its definition 52
Listeners and JDK 1. 1 z. Listener Õresponsible for processing UI events Õspecifies actions that corresponds to an event z. JDK 1. 1 Õcode for listeners made explicit Õneed to associate a listener for every visual object that the user interacts with Õlistener should implement method(s) that specify corresponding actions 53
The Applet as the Listener z. Follows JDK 1. 0. 2 event model z. What needs to be done Õinit() method: as before but associate applet as listener for both buttons (add. Action. Listener(this)) Õapplet implements Action. Listener interface xdefine action. Performed() instead of action() xuse e. get. Source() instead of e. target to distinguish between buttons pressed z. Problems not addressed 54
“Third party” Listener z. Different listener for each button ÕListeners are separate objects ÕTwo different definitions of action. Performed() ÕNo need to distinguish between buttons z. What needs to be done Õcreate listener objects Õadd the objects as listeners for the buttons Õuse anonymous classes 55
The Button as the Listener z. Create a new class (Active. Button) Õclass extends Button and implements Action. Listener (contains action. Performed()) Õaction. Performed() contains call to on. Click() Õadd. Action. Listener(this) in constructor of class z. Applet instantiates Active. Button Õon. Click() or action. Performed() is overridden as appropriate 56
Who should be the Listener? z. The applet Õno advantage except that old jdk 1. 0. 2 code translates easily to this technique z. Third party Õclearly indicates the role of the listeners z. Active. Button Õencapsulates listener-related activity Õapplet code easier to read 57
- Slides: 57