1 The complete Circle class public class Circle { public double x,y; // center coordinates public...

57
1 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; } }

Transcript of 1 The complete Circle class public class Circle { public double x,y; // center coordinates public...

Page 1: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

1

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; }}

Page 2: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

2

Using the Circle class

public class TestCircle { 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()); }}

Page 3: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

3

The this keyword

this refers to the current objectIn the Circle class, the following

definitions for area() are equivalent:public double area() { return 3.14 * r * r; }public double area() { return 3.14 * this.r * this.r; }

Using the keyword clarifies that you are referring to a variable inside an object

Page 4: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

4

Constructors

A constructor is a special type of methodhas the same name as the class

It is called when an object is creatednew Circle(); // “calls” the Circle()

methodIf no constructor is defined, a default

constructor that does nothing is implemented

Page 5: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

5

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; } ...}

Page 6: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

6

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 } ...}

Page 7: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

7

Using the different constructors

Circle c, d;c = new Circle();// radius of circle has been set to 1.0System.out.println(c.area());d = new Circle(1.0,1.0,5.0);// radius of circle has been set to 5.0System.out.println(d.area());

Page 8: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

8

Method Overloading

In Java, it is possible to have several method definitions under the same name but the signatures should be different

Signature:the name of the methodthe number of parametersthe types of the parameters

Page 9: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

9

Syntax Summary

Constructor without a parameterpublic classname() {

*body of the constructor}

Page 10: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

10

Syntax Summary

Overloading constructorspublic classname(type variable-

name) {*body of constructor

}public classname(

type variable-name, type variable-name) {*body of constructor

}

Page 11: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

11

Encapsulation

A key OO concept: “Information Hiding”

Key pointsThe 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

Page 12: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

12

Access Modifiers

publica public variable/method is available for

use outside the class it is defined inprivate

a private variable/method may be used only within the class it is defined in

Page 13: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

13

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

Page 14: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

14

Outside accessto private data

No direct accessDefine (public) set and get methods

instead or initialize the data through constructors

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

Page 15: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

15

Set and Get Methods

Variables/attributes in a class are often not declared public

Instead:define use a (public) set method to

assign a value to a variabledefine a get method to retrieve that

valueConsistent with encapsulation

Page 16: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

16

Set and Get Methods for Radius

public class Circle { // ... private double r; // radius // … public void setRadius(double r) { this.r = r; } public double getRadius() { return this.r; } // ...}

Page 17: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

17

Inheritance

Page 18: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

18

Subclasses and Inheritance

Inheritance:programming language feature that

allows for the implicit definition of variables/methods for a class through an existing class

In Java, use the extends keywordpublic class B extends A { … }objects of subclass B now have access*

to variables and methods defined in A

Page 19: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

19

The EnhancedCircle class

public class EnhancedCircle extends Circle { // as if area(), circumference(), setRadius() and getRadius()

// automatically defined; x,y,r are also present (but are private // to the the Circle class)

private int color; public void setColor(int c) { color = c; } public void draw() { … } public double diameter() { return getRadius()*2; }

}

Page 20: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

20

Using a Subclass

EnhancedCircle c;c = new EnhancedCircle(); // Circle() constructor

// implicitly invoked

c.setColor(5);c.setRadius(6.6);System.out.println(c.area());System.out.println(c.diameter());c.draw();

Page 21: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

21

Applets and Inheritance

Java Applets that we write extend the Applet class (defined in package java.applet)

Methods such as add() (for adding visual components) are actually methods available in the Applet class

init(), action(), and paint() are also available but can be overridden

Page 22: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

22

Class Hierarchy

Subclass relationship forms a hierarchyExample: TextField class

TextField extends TextComponent which extends Component which extends Object

Object is the topmost class in JavaExercise (use javap):

determine where the methods setText(), getText(), hide(), and show() are defined

Page 23: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

23

Method Overriding

A method (with a given signature) may be overridden in a subclass

Suppose class B extends Alet void operate() be a method defined

in Avoid operate() may be defined in Bobjects of class A use A’s operate()objects of class B use B’s operate()

Page 24: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

24

Dynamic Binding

Let A be a superclass of subclasses B and C

A variable of class A may refer to instances of A, B, and C

Java facilitates the calling of the appropriate method at run time

ExampleA v; … v.operate();

Page 25: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

25

Constructors and Superclasses

Suppose B extends Anew B() calls B’s constructorhow about A’s constructor ?

Rulethe constructor of a superclass is always

invoked before the statements in the subclass’ constructor are executed

Page 26: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

26

super()

Used to call a superclass’ constructorImplicitly included when not indicated

If B extends A, the following are equivalent:

public B() { public B() {

// body of constructor super();

} // body of constructor

}

Page 27: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

27

Calling a particular Constructor

Use super with parameters if a particular constructor should be called

Example:public class BlueButton extends Button {

public BlueButton(String s) {

super(s); // without this, super() is called (label-less)

setBackground(Color.blue);

} …

}

Page 28: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

28

Default Constructors

When no constructors are defineda default constructor with no

parameters is implicitly includedIf at least one constructor is defined,

with or without parametersa default constructor will not apply

Page 29: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

29

Syntax Summary

Extends and Superpublic class subclass extends superclass {

public subclassconstructor(...) {super(...); *body of constructor

}...

}

Page 30: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

30

Abstract Classes and Interfaces

Page 31: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

31

“Incomplete” Classes

Objects vs “concepts”Example: Circle and Shape

circles are shapes (Circle extends Shape)

shapes (such as circle) have area and circumference

how are area() and circumference() defined at the level of Shape?

Shape has incomplete definitions

Page 32: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

32

The Shape class

One optionmake area() and circumference() methods

that do nothing (perhaps return 0.0)Circle could extend shape and then

override these methodsproblems ?

Another option available in Javaabstract class

Page 33: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

33

Abstract Class

Same as classbut it is possible to omit method bodiessyntax:

abstract before class (and method headers)semicolon at the end of the method headers

Rulesmay declare variables of abstract classesinstantiation not possible (new will not work)subclasses must override incomplete

methods

Page 34: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

34

The Shape class

public abstract class Shape { private int color; public void setColor(int c) { color = c; } public abstract double circumference(); public abstract double area();}

Page 35: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

35

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; }}

Page 36: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

36

Using Shape and Circle

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

Page 37: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

37

Another Example:Function Plotter

Define an abstract class FunctionPlotter that plots a mathematical function f()a method plot() plots a function f() by

evaluating f() on some x valuesmake f() an abstract method, i.e.,

public abstract double f(double x);Next, define classes that extend

FunctionPlotter and complete the definition of f()

Page 38: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

38

Function Plotter, continued

LinePlotter defines f() as follows:public double f(double x) { return x; }

SquarePlotter defines f() as follows:public double f(double x) { return x*x; }

Note: LinePlotter, SquarePlotter (and Circle, in the previous example) are called concrete classes

Page 39: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

39

Why Use Abstract Classes?

More robust codeno need to use “new” on anything it

shouldn’t be used onEnforces 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

Page 40: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

40

Interface

None of the methods have bodiesInstance variables not allowedSyntax

interface not classno need to put abstract before method

headersimplements not extends on the

complete (concrete) class

Page 41: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

41

Rules on Interfaces

May declare variables whose type is an interfaceobjects that are instances of classes

that implement the interface may be referred to by such variables

Instantiation not possibleImplementing class must define all

methods

Page 42: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

42

Example

public interface Switch { public void turnOn(); public void turnOff(); public boolean isOn();}public class Computer implements Switch { // must define turnOn(), turnOff(), and isOn() in this class

...}

Page 43: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

43

Notes on Interfaces

Interface variables can be declarede.g., Switch s;

Interfaces cannot be instantiatedInterface variables may refer to objects

of classes that implement the interfacee.g., s = new Computer();

A class may implement several interfaces

Page 44: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

44

Multiple Inheritance

Other OO languages such as C++ allow several superclasses for a given classnot possible in Java

Implementation problemscommon members in superclasses

In Javause interfacesit is possible to implement several interfaces

with no “conflicts”

Page 45: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

45

Anonymous Classes

Feature available in JDK 1.1 or higher versions of Java

Useful whenOnly one object of the concrete class

needs to be createdIt is not too important to have a name

for the concrete class

Page 46: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

46

Back to FunctionPlotter Example

Without anonymous classes, the LinePlotter class would look like thispublic class LinePlotter extends FunctionPlotter { public double f(double x) { return x; }}

And then, in some main program …LinePlotter lp = new LinePlotter();lp.plot();

Page 47: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

47

Using Anonymous Classes

FunctionPlotter lp = new FunctionPlotter() { public double f(double x) { return x; }}lp.plot();

// no need to explicitly define a LinePlotter class

Page 48: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

48

Syntax Summary

Anonymous classesabstractclassorinterface var =

new abstractclassorinterface() {// complete the definitions of abstract

// methods here }

Page 49: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

49

The Java Event Models

Page 50: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

50

Event-Driven Programming in Java

Specifying actions for events performed on the GUImost common example: clicking on a

buttonThe Java Event Models

JDK 1.0.2 (deprecated)JDK 1.1 and the new event model

Page 51: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

51

Sample Applet: HideAndShow

Visual objectstext field with some texttwo buttons

Actions performedhide button causes text field to

disappearshow button makes text field reappear

Page 52: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

52

JDK 1.0.2

What needs to be doneinit() method: create visual components

and add them to the appletaction(): determine which button was

clicked and indicate associated actionProblems

nested if-statement in action() inefficientcode associated with visual object far

from its definition

Page 53: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

53

Listeners and JDK 1.1

Listenerresponsible for processing UI eventsspecifies actions that corresponds to an

eventJDK 1.1

code for listeners made explicitneed to associate a listener for every visual

object that the user interacts withlistener should implement method(s) that

specify corresponding actions

Page 54: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

54

The Applet as the Listener

Follows JDK 1.0.2 event modelWhat needs to be done

init() method: as before but associate applet as listener for both buttons (addActionListener(this))

applet implements ActionListener interfacedefine actionPerformed() instead of action()use e.getSource() instead of e.target to

distinguish between buttons pressed

Problems not addressed

Page 55: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

55

“Third party” Listener

Different listener for each buttonListeners are separate objectsTwo different definitions of

actionPerformed()No need to distinguish between buttons

What needs to be donecreate listener objectsadd the objects as listeners for the buttonsuse anonymous classes

Page 56: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

56

The Button as the Listener

Create a new class (ActiveButton)class extends Button and implements

ActionListener (contains actionPerformed())actionPerformed() contains call to onClick()addActionListener(this) in constructor of

class Applet instantiates ActiveButton

onClick() or actionPerformed() is overridden as appropriate

Page 57: 1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()

57

Who should be the Listener?

The appletno advantage except that old jdk1.0.2

code translates easily to this techniqueThird party

clearly indicates the role of the listenersActiveButton

encapsulates listener-related activityapplet code easier to read