Classes and Objects in Java - PowerPoint PPT Presentation

1 / 63
About This Presentation
Title:

Classes and Objects in Java

Description:

variable r that indicates its radius. method area() that computes its area ... Button: clickable visual object. Label: text. TextField. contains editable text ... – PowerPoint PPT presentation

Number of Views:56
Avg rating:3.0/5.0
Slides: 64
Provided by: mathAd
Category:

less

Transcript and Presenter's Notes

Title: Classes and Objects in Java


1
Classes and Objectsin Java
2
Variables 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())

3
The 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

4
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())

5
The 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

6
Constructors
  • 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

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

8
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
  • ...

9
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,1.0,5.0)
  • // radius of circle has been set to 5.0
  • System.out.println(d.area())

10
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 method
  • the number of parameters
  • the types of the parameters

11
Encapsulation
  • 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

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
  • 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

14
Set and Get Methods
  • public class Circle
  • // ...
  • private double r // radius
  • //
  • public void setRadius(double r) this.r r
  • public double getRadius() return this.r
  • // ...

15
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 keyword
  • public class B extends A
  • objects of subclass B now have access to
    variables and methods defined in A

16
The 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

17
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()

18
Life 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

19
Applets
  • 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

20
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

21
Class 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

22
Applet Class Hierarchy
23
Visual Programming
24
The Java Abstract Windowing Toolkit (AWT)
  • Components
  • Label, Button, TextField, TextArea, Panel
  • Others (self-study)
  • Layout Managers
  • FlowLayout, GridLayout, BorderLayout
  • CardLayout, GridBagLayout (self-study)

25
Components
  • 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()

26
Designing 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)

27
GUI 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)
  • // ...

28
Events
  • 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

29
Handling 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()
  • //

30
Containers
  • 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

31
Label
  • 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()

32
Button
  • Button()
  • Button(String str)
  • void setLabel(String str)
  • String getLabel()
  • implement ActionListener interface
  • interface defines actionPerformed() method
  • obtain label by the getActionCommand()

33
TextField
  • 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)

34
TextField
  • Boolean isEditable
  • void setEditable(boolean canEdit)
  • void setEchoChar(char ch)
  • boolean echoCharIsSet()
  • char getEchoChar()

35
TextArea
  • 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

36
TextArea
  • 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)

37
Layout 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

38
FlowLayout
  • 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))

39
GridLayout
  • GridLayout()
  • GridLayout(int numRows, int numColumns)
  • GridLayout(int numRows, int numColumns, int horz,
    int vert)

40
BorderLayout
  • BorderLayout()
  • BorderLayout(int horz, int vert)
  • Regions
  • BorderLayout.CENTER
  • BorderLayout.EAST
  • BorderLayout.WEST
  • BorderLayout.NORTH
  • BorderLayout.SOUTH
  • void add(Component compObj, Object region)

41
Using 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)

42
Window 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

43
Window 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

44
Frame
  • 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

45
Creating 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)

46
Graphics 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

47
Lines 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)

48
Ellipses, 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)

49
Polygons
  • void drawPolygon(int x, int y, int numPoints)
  • void fillPolygon(int x, int y, int numPoints)

50
Simple 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

51
About 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

52
Creating Classes and Objects
53
Something 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)

54
Bank 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
    )

55
BankAccount 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
56
Using 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() )

57
GraphicsIOApplet
  • 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

58
Shapes 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

59
Interfaces
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

60
Shape 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)

61
Crosshair 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)
62
Defining 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()

63
Using 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
Write a Comment
User Comments (0)
About PowerShow.com