Title: Classes and Objects in Java
1Classes and Objectsin Java
2Variables and Objects
- Let Circle be a class with
- variable r that indicates its radius
- method area() that computes its area
- Declaration Circle c
- Instantiation c new Circle()
- Usage c.r 5.5
- System.out.println(c.area())
3The complete Circle class
- public class Circle
- public double x,y // center coordinates
- public double r // radius
- // the methods
- public double circumference()
- return 23.14r
- public double area()
- return 3.14rr
4Using 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())
-
5The this keyword
- this refers to the current object
- In 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
6Constructors
- A constructor is a special type of method
- has the same name as the class
- It is called when an object is created
- new Circle() // calls the Circle() method
- If no constructor is defined, a default
constructor that does nothing is implied - Constructors with parameters can be specified
7A 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
-
- ...
8A 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
-
- ...
9Using 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,1.0,5.0)
- // radius of circle has been set to 5.0
- System.out.println(d.area())
10Method 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 method
- the number of parameters
- the types of the parameters
11Encapsulation
- A key OO concept Information Hiding
- Key points
- The user of an object should have access to
methods that are essential the interface - Unnecessary implementation details should be
hidden from the user - The object is encapsulated
- In Java, use public and private
12The 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
13Outside access to private data
- No direct access
- Define (public) set and get methods instead or
initialize the data through constructors - Why?
- If you change your minds about the names and even
the types of these private data, the code using
the class need not be changed
14Set and Get Methods
- public class Circle
- // ...
- private double r // radius
- //
- public void setRadius(double r) this.r r
- public double getRadius() return this.r
- // ...
15Subclasses 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 keyword
- public class B extends A
- objects of subclass B now have access to
variables and methods defined in A
16The EnhancedCircle class
- public class EnhancedCircle extends Circle
- // as if x, y, r, area(), circumference(),
setRadius() - // and getRadius() automatically defined
- private int color
- public void setColor(int c) color c
- public void draw()
- public int diameter() return getRadius()2
17Using 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()
18Life Cycle of an object
- 1) Creating Objects
- - declaration, instantiation, initialization
- 2) Using Objects
- - manipulate or inspect its variables
- - call its methods
- 3) Cleaning up unused objects
- - garbage collection
19Applets
- Writing applets from scratch
- Steps
- extend Javas Applet class
- define variables for visual objects and other
data - define init() method to set up visual objects,
action() method to process events, paint() method
for placing graphics on the applet
20Applets 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
21Class Hierarchy
- Subclass relationship forms a hierarchy
- Example TextField class
- TextField extends TextComponent which extends
Component which extends Object - Object is the topmost class in Java
22Applet Class Hierarchy
23Visual Programming
24The Java Abstract Windowing Toolkit (AWT)
- Components
- Label, Button, TextField, TextArea, Panel
- Others (self-study)
- Layout Managers
- FlowLayout, GridLayout, BorderLayout
- CardLayout, GridBagLayout (self-study)
25Components
- Button clickable visual object
- Label text
- TextField
- contains editable text
- methods setText() and getText()
- TextArea - multiline editor
- Panel
- may contain other visual components
- methods setLayout() and add()
26Designing a Visual Interface for an Applet
- Declare variables for the different visual
components to be placed on the applet - In init() method,
- create visual components (use new)
- establish layout manager (use setLayout()) --
default for applets FlowLayout - add visual components (use add())
- nested layouts possible (use Panels)
27GUI Example
- public class HideMessage extends Applet
- Button hidebutton
- TextField message
- public void init()
- setLayout(new FlowLayout())
- hidebutton new Button(Hide)
- message new TextField(Hello)
- add(hidebutton) add(message)
- // ...
28Events
- The Event class and Event objects
- represents an event
- target attribute that represents object that
was involved in the event - action() method of Applet
- called when a visual event occurs
- includes an event object as a parameter
29Handling Events
- In action method,
- determine which object (button, text field,
others) was involved during the event and then
specify what happens next - Example
- public boolean action(Event e, Object o)
- if (e.target hidebutton)
- message.hide()
- //
30Containers
- Components that can contain other components
- Container is a class of which Panel and Applet
are subclasses - setLayout() and add() are container methods
- Frame another container example
- use when you want a visual application
31Label
- Label() - blank label
- Label(String str) - str is left-justified
- Label(String str, int how) - how should be any of
Label.LEFT, Label.RIGHT or Label.CENTER - void setText(String str)
- String getText()
- void setAlignment(int how)
- int getAlignment()
32Button
- Button()
- Button(String str)
- void setLabel(String str)
- String getLabel()
- implement ActionListener interface
- interface defines actionPerformed() method
- obtain label by the getActionCommand()
33TextField
- TextField()
- TextField(int numChars)
- TextField(String str)
- TextField(String str, int numChars)
- String getText()
- void setText(String str)
- String getSelectedText()
- void select(int startIndex, int endIndex)
34TextField
- Boolean isEditable
- void setEditable(boolean canEdit)
- void setEchoChar(char ch)
- boolean echoCharIsSet()
- char getEchoChar()
35TextArea
- TextArea()
- TextArea(int numLines, int numChars)
- TextArea(String str)
- TextArea(String str, int numLines, int numChars)
- TextArea(String str, int numLines, int numChars,
int sBars) - sBars can be SCROLLBARS_BOTH, SCROLLBARS_NONE,
SCROLLBARS_HORIZONTAL_ONLY or SCROLLBARS_VERTICAL_
ONLY
36TextArea
- Supports the methods
- getText(), setText(), getSelectedText(),
select(), isEditable(), setEditable - void append(String str)
- void insert(String str, int index)
- void replaceRange(String str, int startIndex, int
endIndex)
37Layout Managers
- viod setLayout(LayoutManager layoutObj)
- FlowLayout
- objects are placed row by row, left to right
- GridLayout
- divides container into an m by n grid
- BorderLayout
- divides container into 5 parts
- Center, North, South, East, West
38FlowLayout
- FlowLayout()
- FlowLayout(int how)
- FlowLayout(int how, int horz, int vert)
- how should be any of FlowLayout.LEFT,
FlowLayout.CENTER, FlowLayout.RIGHT - example
- // set left-aligned flow layout
- setLayout(new FlowLayout(FlowLayout.LEFT))
39GridLayout
- GridLayout()
- GridLayout(int numRows, int numColumns)
- GridLayout(int numRows, int numColumns, int horz,
int vert)
40BorderLayout
- BorderLayout()
- BorderLayout(int horz, int vert)
- Regions
- BorderLayout.CENTER
- BorderLayout.EAST
- BorderLayout.WEST
- BorderLayout.NORTH
- BorderLayout.SOUTH
- void add(Component compObj, Object region)
41Using Insets
- Leave a small amount of space between the
container that holds your components and the
window that contains it. - Insets(int top, int left, int bottom, int right)
42Window Fundamentals
- Component
- - abstract class that encapsulates all of the
attributes of a visual component - Container
- - subclass of component
- - has additional methods that allow other
components to be nested within it. - Panel
- - concrete subclass of container
- - no additional methods, just implements
container - - superclass of Applet
43Window Fundamentals
- Window
- - class creates a top-level window
- Frame
- - encapsulates what is commonly thought of as a
window - - subclass of window with title bar, menu bar,
borders, and resizing corners
44Frame
- Frame()
- Frame(String title)
- void setSize(int newWidth, int newHeight)
- void setSize(Dimension newSize)
- Dimension getSize()
- void setVisible(boolean visibleFlag)
- void setTitle(String newTitle)
- close a frame window
45Creating a Frame Object for a Java Application
- In some main() method,
- create the frame object
- to display frame, call setVisible on that object
- Example
- public static void main(String args)
- MyFrame f new MyFrame()
- f.setVisible(true)
46Graphics in Java
- The Java AWT supports graphics
- Graphics is a class
- a Graphics object can be viewed as something that
you can draw on e.g., the region of an applet or
frame - public void paint(Graphics g) method
- contains drawing commands
- called when system needs to redraw the applet or
frame
47Lines and Rectangles
- void drawLine(int startX, int startY, int endX,
int endY) - void drawRect(int top, int left, int width, int
height) - void fillRect(int top, int left, int width, int
height) - void drawRoundRect(int top, int left, int width,
int height, int xDiam, int yDiam) - void fillRoundRect(int top, int left, int width,
int height, int xDiam, int yDiam)
48Ellipses, Circles and Arcs
- void drawOval(int top, int left, int width, int
height) - void fillOval(int top, int left, int width, int
height) - void drawArc(int top, int left, int width, int
height, int startAngle, int sweepAngle) - void fillArc(int top, int left, int width, int
height, int startAngle, int sweepAngle)
49Polygons
- void drawPolygon(int x, int y, int numPoints)
- void fillPolygon(int x, int y, int numPoints)
50Simple Animation
- Define an int variable y as an attribute for the
applet - Arrange it so that y is incremented by 10 when a
button is pressed, call repaint() after
incrementing - Initialize y to zero in the init() method
- In paint(), g.drawString(Hello, y, 50)
- String moves as you click on the button
51About paint()
- Describes current picture for the applet (or
frame) - Not cumulative
- previous string in the animation example drawn
disappears when you refresh the drawing - repaint() calls paint() and is in fact called
automatically every few seconds
52Creating Classes and Objects
53Something to think about
Answer c 150000 but z 450000 because y
points to the same object as x
- Suppose
- long a 150000
- long b a
- a a 300000
- long c b
-
- BankAccount x new BankAccount( 150000, Jose
Velarde ) - BankAccount y x
- x.deposit( 300000 )
- long z y.getBalance()
- What is the final value of c? z? Why?
- (you can try running a similar example using
Circle and setRadius / getRadius)
54Bank Account Object
How do we define a BankAccount class?
- State (aka Fields)
- balance the current amount of money in the
account - owner name of person owning the account
- Behavior (aka Methods)
- new BankAccount( initialAmount, owner ) create
account - getBalance() returns an integer
- deposit( amount ) adds amount to balance
- withdraw( amount ) subtracts amount from balance
- getOwner() returns the name of the owner
- Usage
- declaration BankAccount x
- Instantiation x new BankAccount(150000, J.
Velarde) - Using fields and methods x.deposit( 600000000
)
55BankAccount class (balance only)
- public class BankAccount
- private long balance // current amount
- // constructor
- public BankAccount( long balance )
- this.balance balance
-
- public long getBalance()
- return balance
-
- public void deposit( long amount )
- balance amount
-
- public void withdraw( long amount )
- balance - amount
-
Fields
Methods
56Using the BankAccount class
- public class TestBankAccount
- public static void main(String args)
- BankAccount x
- x new BankAccount( 1000 )
- x.deposit( 1000 )
- System.out.println( x.getBalance() )
- x.withdraw( 500 )
- System.out.println( x.getBalance() )
-
57GraphicsIOApplet
- A drawing version of InputOutputApplet
- Extend this class instead of Applet or
InputOutputApplet - call addGraphics() in setup()
- create initial graphics and text int
initOutputs() method - create and draw Shape objects
- e.g., Circle, Line, Point, Rectangle, GraphicText
58Shapes and Methods
- Point
- new Point( x, y ), getX, getY, setX, setY, setXY
- Line
- new Line( startX, startY, endX, endY )
- getStart(), getEnd(), setStart( x, y ), setEnd(
x, y ) - Circle
- new Circle( x, y, radius )
- getCenter(), getRadius(), setCenter( x, y ),
setRadius( r ) - Rectangle
- new Rectangle( leftX, upperY, width, height )
- getULCorner(), getWidth(), getHeight(),
- setULCorner( x, y ), setWidth(), setHeight()
- GraphicText
- new GraphicText( leftX, upperY, text )
- getULCorner(), getText(), setULCorner( x, y ),
setText( text ) - All Shapes have move( dx, dy ) method
59Interfaces
Idea We can make our own Shape objects!
- The public methods of a class constitutes its
interface to the outside world - In Java, we can classify objects in terms of
their interface - e.g., Shape interface
- void move( int dx, int dy )
- void paint( java.awt.Graphics g )
- the draw(Shape) method in GraphicsIOApplet takes
objects that implement these methods - Point, Circle, Line, etc. each implements Shape
- has code for move and paint
60Shape interface
- public interface Shape
- public void move( int dx, int dy )
- public void paint( java.awt.Graphics g )
-
- An interface definition is like a class
definition, but - No fields
- No method bodies
- Defines what objects of type Shape can do
(interface), but does not define how they do it
(implementation)
61Crosshair Class
- public class Crosshair implements Shape
- private Point center
- private int r
- private Line hline, vline
- // constructors
- public Crosshair(Point center, int r)
- set( center, r )
-
- public Crosshair( int x, int y, int r )
- this( new Point( x, y ), r )
- // this can be used to call another
version // of a constructor within a constructor -
-
- public void set( Point center, int r )
- this.center center
- this.r r
- this.hline new Line( center.getX() - r,
center.getY(), - center.getX() r,
center.getY() ) - this.vline new Line( center.getX(),
center.getY() - r,
public void move(int x, int y)
center.move(x, y) hline.move(x, y)
vline.move(x, y) public void
paint(java.awt.Graphics g) hline.paint(g)
vline.paint(g)
62Defining the Person Class
- Use Crosshair as an example
- Fields
- Built-in Shapes (Circles, Lines, etc.)
corresponding to different parts of body - A Point for reference position? (or use one of
the shapes) - Methods
- move just call move on all the shapes
- paint just call paint on all the shapes
- raiseLeftArm(), lowerLeftArm(), raiseRightArm(),
lowerRightArm(), raiseLeftLeg(), lowerLeftLeg()
63Using the Person Class
- Create 3 persons, and draw them on screen
- onButtonPressed make them do jumping-jacks by
calling raiseLeftHand(), raiseLeftFoot(), etc. - Make the code even simpler by defining jumpUp()
and jumpDown() methods in terms of
raiseLeftHand(), raiseLeftFoot(), etc. - Optional have an input field that allows you to
create N Persons. - use arrays of Persons (more about this next
Lecture) - use clear() method in GraphicsApplet to get rid
of old drawn Shapes