Basic 2 Classes and Objects - PowerPoint PPT Presentation

1 / 28
About This Presentation
Title:

Basic 2 Classes and Objects

Description:

Objects: several Person instances are all around you. Trivial ... p1.weight = -20; // unreal. Solution: Have class modify attribute. Allows sanity checks. ... – PowerPoint PPT presentation

Number of Views:25
Avg rating:3.0/5.0
Slides: 29
Provided by: mlin
Category:

less

Transcript and Presenter's Notes

Title: Basic 2 Classes and Objects


1
Basic -2Classes and Objects
2
Classes and Objects
  • A class is a complex data TYPE
  • An object is an instance of a class.
  • Example
  • Class Person
  • Objects several Person instances are all around
    you

3
Trivial Example Class Person
  • A Person has some properties
  • Attributes or fields
  • In addition it may have some behavior
  • methods
  • A java class defines properties and behavior
    common to all people (all Person objects)
  • Each person gets their own field copies

4
Class Person - example
  • class Person
  • String name
  • int height // in inches
  • int weight // in pounds
  • // well worry about methods later
  • void setWeight(int newWeight)
  • void setHeight(int newHeight)

5
Objects
  • An object is an instance of a class type
  • An object variable is a reference to the objects
    data structure
  • Object variable can be seen as a pointer
  • Declaring an object variabile ! creating an
    object
  • Declaration provides a null pointer
  • Must create an object with the newkeyword
  • Calls a constructor method of the class
    (optionally with arguments)
  • Dynamic allocation

Variable declaration
Person p1 p1 new Person() p1.name your
name
Object instantiation
6
Object Variables
  • Multiple variables can point to same object
  • A variable can point to NO object
  • its value is null
  • NOTE passing an object as parameter in a method
    actually passes a copy of the reference
  • Method manipulates the same referenced object

Person p1, p2 p1new Person()
p1.name John p2 p1
System.out.println(p1.name) System.out.println(p2
.name) Person p3 p3new
Person() p3.name Dan p2p3
System.out.println(p2.name)
7
Illustration
name John height 0 weight 0
p1
p2
name Dan height 0 weight 0
p3
Java graciously initializes primitive fields for
you
8
Object creation caveats
  • What if we dont use new?
  • Person p
  • System.out.println(p.name)
  • Hgtjavac Person.java
  • Person.java15 Variable p may not have been
    initialized.
  • System.out.println(p.name)
  • 1 error

9
Second Try
  • Person p new Person()
  • p null
  • System.out.println(p.name)
  • Compilation works fine but
  • Hgtjava Person
  • Exception in thread "main" java.lang.NullPointerEx
    ception
  • at Person.main(Person.java16)

10
Object equality
  • RECALL variables are references

Person p1 new Person() Person p2 new
Person() p1.name Jane p2.name
Jane If(p1 p2) System.out.println(Same!")
else System.out.println(Different!")
Person Jane
p1
Person Jane
p2
11
More on equality equals()
  • All classes are equipped with a method equals()
  • For comparing objects of same class
  • Can be (re-)defined wrt class logic

boolean equals(Person otherPerson) if
name.equals(otherPerson.name) System.out.printl
n(Same!") return true
System.out.println(Different!") return
false
12
Object Destruction
  • Programmer cannot explicitly destroy an
    instantiated object
  • JVM takes care of garbage collection
  • Implicitly frees up memory from useless objects
  • Object is useless when program keeps no more
    references to it
  • e.g when program exits the context where object
    was created (block, method variables)
  • Or when variables point to other objects or are
    assigned the null value

13
Lets play around with Person
  • p1.weight 200 // bad but dealable
  • p1.weight 700 // unfortunate, but possible
  • p1.weight -20 // unreal
  • Solution Have class modify attribute. Allows
    sanity checks.
  • Provide that behavior through a method
  • p1.setWeight(700) // OK. Weight is now 700.
  • p1.setWeight(-20)
  • Error, weight must be positive number
  • // weight still 700

14
Solution?
  • class Person
  • void setWeight(int newWeight)
  • if (newWeight lt 0)
  • System.err.println(
  • Error, weight must be positive number)
  • else
  • weight newWeight

15
New problem
  • p1.setWeight(-20)
  • Error, weight must be positive number
  • p1.weight -20 // Yo, Im the boss
  • Assigning weight directly bypasses sanity check
    by the setWeight() method. We still have a
    problem.
  • Solution change attribute visibility to make the
    bare weight attribute inaccessible from outside
    Person

16
New solution
  • Class Person
  • private String name
  • private int height // in inches
  • private int weight // in pounds
  • public void setWeight(int newWeight)
  • if (newWeight lt 0)
  • System.err.println(
  • Error, weight must be positive number)
  • else
  • weight newWeight

Within same class no dot notation and no
visibility issues
17
New solution in action
  • class Test
  • public static void main(String args)
  • Person p1 new Person()
  • p1.weight 20
  • gtjavac Test.java
  • gtTest.java4 Variable weight in class Person not
    accessible from class Test.
  • p1.weight 20
  • 1 error
  • Denied!

18
Finish up
  • Need to add a getWeight(), since we can no longer
    access weight directly
  • public int getWeight(void)
  • return weight
  • Also, need get() and set() functions for name and
    height.

19
Accessor Functions for Encapsulation
  • Generally make fields private and provide public
    getField() and setField() accessor functions.
  • For this course ALWAYS
  • unless theres a specific reason not to
  • Usually there isnt
  • Need to justify explicitly otherwise!
  • Encapsulation keeps programs tidy
  • Enables clear definition of interactions between
    classes
  • Public parts of a class represents its
    Application Programming Interfaces (API)
  • Private parts hide details of the class
    implementation
  • If interface remains stable, even if
    implementation changes, the rest of application
    is unaffected
  • Example height in cm. and weight in Kg.

20
More on Visibility
/ Represents a 2d geometric point / package
2d class Point private float x,y //
coordinates public Point(float coordX, float
coordY) xcoordX ycoordY public
void move(float dX, float dY) xdX
ydY public String desc() return
Point (" x ", " y ")"
  • Methods / Attributes
  • public
  • private
  • package (default)
  • protected

Constructor with parameters
At-a-glance look at the class API
21
Constructors
public class Point private float x,y
public Point() xy0 // same as default
public Point(float coordX,
float coordY) xcoordX ycoordY
public Point(float xy) this(xy,xy)
  • Multiple constructors with different sets of
    parameters
  • No need to specify result type
  • new operator invoked with parameters matching
    those of some constructor
  • If programmer provides no constructor, Java
    provides default constructor (no parameters)

Constructor chaining
22
Default Constructor
  • Takes no parameters, initializes everything to
    defaults
  • 0, null etc.
  • Graciously provided by Java for absent-minded
    programmers -)
  • Only exists if there are no explicitly defined
    constructors
  • Any constructor, even one taking parameters,
    means no default

23
Overloading
  • Multiple constructors is a prominent example of
    overloading
  • Multiple methods can have same name but different
    signatures

public class Point private float x,y
public void move(float dx, float dy) xdx
ydy public void move(float dxy)
move(dxy, dxy)
24
Strings
  • Strings in Java are objects of class
    java.lang.String
  • Java.lang is a fundamental library
  • String has a lot of nice features check it out
    in the javadocs!

char characters H', e', l', 'l',
'o' String salutationnew String(characters) Sy
stem.out.println(salutation) System.out.println(s
alutation.length()) String s
World salutation s System.out.println
(salutation)
25
Comparing Strings
  • if (s1 s2) .
  • NO!
  • if (s1.equals(s2))
  • Prominent case of equals() vs.

26
Turning objects into Strings
  • All classes have a method toString() to provide a
    textual description of objects
  • Can be (re-)defined wrt class logic

public class Person ... public String
toString() String ret ret name is tall
ret height ret inches and weighs
ret weight ret pounds. return
ret ...
27
Turning objects into Strings
  • toString()can be invoked implicitlly
  • When object is used within String manipulation
    operations

Person assistantnew Person(Mike) System.out.p
rintln(the assistant is " assistant)
28
Summary
  • Introduction to the Java language
  • What is Java, what is a Java program
  • Style, Javadocs
  • Language basics
  • Types, variables
  • Classes, objects, arrays
  • Visibility and encapsulation
  • Some utilities
  • String, toString()
  • System.out
Write a Comment
User Comments (0)
About PowerShow.com