Basic -2 Classes and Objects

Download Report

Transcript Basic -2 Classes and Objects

Basic -2
Classes and Objects
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

Trivial Example: Class
Person

A Person has some properties


In addition it may have some behavior



Attributes or fields
methods
A java class defines properties and behavior
common to all people (all Person objects)
Each person gets their own field copies
Class Person - example
class Person {
String name;
int height; // in inches
int weight; // in pounds
// we’ll worry about methods later
void setWeight(int newWeight) { }
void setHeight(int newHeight){ }
}
Objects
Variable
declaration
Person p1;
p1 = new Person();
p1.name = “ your name”;
Object
instantiation

An object is an instance of a class type

An object variable is a reference to the
object’s 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 new
keyword
 Calls a constructor method of the class
(optionally with arguments)
 Dynamic allocation
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;
p1=new
Person();
p1.name = “John”;
p2 = p1;
System.out.println(p1.name);
System.out.println(p2.name);
{
Person p3;
p3=new Person();
p3.name = “Dan”;
p2=p3;
System.out.println(p2.name);
}
Illustration
p1
name: “John”
height: 0
weight: 0
p2
p3
name: “Dan”
height: 0
weight: 0
Java graciously
initializes primitive
fields for you
Object creation caveats

What if we don’t use new?
Person p;
System.out.println(p.name);
H:>javac Person.java
Person.java:15: Variable p may not have been
initialized.
System.out.println(p.name);
^
1 error
Second Try
Person p = new Person();
p = null;
System.out.println(p.name);

Compilation works fine but …
H:>java Person
Exception in thread "main" java.lang.NullPointerException:
at Person.main(Person.java:16)
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!");
p1
p2
: Person
“Jane ”
: Person
“Jane”
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.println(“Same!");
return true;
}
System.out.println(“Different!");
return false;
}
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
Let’s 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
Solution? …
class Person {
…
void setWeight(int newWeight) {
if (newWeight < 0)
System.err.println(
“*** Error, weight must be
positive number”);
else
weight = newWeight;
}
… New problem
p1.setWeight(-20);
*** Error, weight must be positive
number
p1.weight = -20;
// Yo, I’m 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
New solution
Class Person {
private String name;
private int height; // in inches
private int weight; // in pounds
public void setWeight(int newWeight) {
if (newWeight < 0)
System.err.println(
“*** Error, weight must be
positive number”);
else
weight = newWeight;
}
}
Within same class no
dot notation and no
visibility issues
New solution in action
class Test {
public static void main(String args[]) {
Person p1 = new Person();
p1.weight = 20;
}
}
>javac Test.java
>Test.java:4: Variable weight in class Person not
accessible from class Test.
p1.weight = 20;
^
1 error
Denied!
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.
Accessor Functions for
Encapsulation


Generally make fields private and provide public
getField() and setField() accessor functions.
For this course – ALWAYS





Encapsulation keeps programs tidy
Enables clear definition of interactions between classes




unless there’s a specific reason not to
Usually there isn’t
Need to justify explicitly otherwise!
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.
More on Visibility

Methods /
Attributes



Point

/** Represents a 2d geometric point
*/
package 2d;
class Point {
public
private
package
(default)
protected
private float x,y; // coordinates
public Point(float coordX, float coordY){
x=coordX;
Constructor with
y=coordY;
parameters
}
public void move(float dX, float dY){
x+=dX;
y+=dY;
}
public String desc(){
return “Point (" + x + ", " + y + ")";
}
- float x,y
+ Point(float, float)
+ move(float dx, float dy)
+ String desc()
}
At-a-glance look at
the class API
Constructors
public class Point {

Multiple constructors with
different sets of parameters



private float x,y;
public Point()
{
x=y=0; // same as default
}
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)
public Point(float coordX,
float coordY)
{
x=coordX; y=coordY;
}
public Point(float xy)
{
this(xy,xy);
}
}
Constructor
chaining
Default Constructor

Takes no parameters, initializes everything
to defaults




0, null etc.
Graciously provided by Java for absentminded programmers ;-)
Only exists if there are no explicitly defined
constructors
Any constructor, even one taking
parameters, means no default
Overloading
Multiple constructors is a
prominent example of overloading
 Multiple methods can have same
name but different signatures
Point {

public class
private float x,y;
public void move(float dx, float dy){
x+=dx;
y+=dy;
}
public void move(float dxy){
move(dxy, dxy);
}
}
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 salutation=new String(characters);
System.out.println(salutation);
System.out.println(salutation.length());
String s = “ World”;
salutation += s;
System.out.println (salutation);
Comparing Strings

if (s1 == s2) {….

NO!

if (s1.equals(s2)) {…

Prominent case of equals() vs. ==
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;
}
...
}
Turning objects into Strings

toString()can be invoked
implicitlly

When object is used within String
manipulation operations
Person assistant=new Person(“Mike”);
System.out.println(“the assistant is: "+ assistant);
Summary

Introduction to the Java language



Language basics




What is Java, what is a Java program
Style, Javadocs
Types, variables
Classes, objects, arrays
Visibility and encapsulation
Some utilities


String, toString()
System.out