Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an...

27
Basic -2 Classes and Objects

Transcript of Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an...

Page 1: 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:

Basic -2Classes and Objects

Page 2: 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:

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

Page 3: 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:

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

Page 4: 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:

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){ }}

Page 5: 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:

Objects 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

Person p1;

p1 = new Person();

p1.name = “ your name”;

Variable declaration

Object instantiatio

n

Page 6: 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:

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

Page 7: 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:

Illustration

p1

p3

name: “John”height: 0weight: 0

name: “Dan”height: 0weight: 0

p2

Java graciously initializes primitive

fields for you

Page 8: 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:

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

Page 9: 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:

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)

Page 10: 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:

Object equality: ==

RECALL: variables are referencesPerson 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 ”

: Person“Jane”

p1

p2

Page 11: 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:

More on equality: equals() All classes are equipped with a

method equals() For comparing objects of same classCan 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;}

Page 12: 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:

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

Page 13: 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:

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

Page 14: 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:

Solution? …

class Person {

void setWeight(int newWeight) {

if (newWeight < 0)

System.err.println(

“*** Error, weight must be positive number”);

else

weight = newWeight;

}

Page 15: 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:

… 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

Page 16: 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:

New solution

Class Person {private String name;private int height; // in inchesprivate int weight; // in pounds

public void setWeight(int newWeight) {if (newWeight < 0)

System.err.println(“*** Error, weight must be positive number”);

elseweight = newWeight;

}} Within same class

no dot notation and no visibility issues

Page 17: 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:

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!

Page 18: 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:

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.

Page 19: 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:

Accessor Functions for Encapsulation

Generally make fields private and provide public getField() and setField() accessor functions.

For this course – ALWAYS unless there’s a specific reason not to Usually there isn’t 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.

Page 20: 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:

More on Visibility

Methods / Attributes public private package (default) protected

/** Represents a 2d geometric point */package 2d;class Point {

private float x,y; // coordinates

public Point(float coordX, float coordY){ x=coordX; y=coordY; } public void move(float dX, float dY){ x+=dX; y+=dY; } public String desc(){ return “Point (" + x + ", " + y + ")"; }}

Constructor with parameters

Point

- float x,y

+ Point(float, float)+ move(float dx, float dy) + String desc() At-a-glance look

at the class API

Page 21: 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:

Constructors 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)

public class Point {

private float x,y;

public Point() { x=y=0; // same as default }

public Point(float coordX, float coordY) { x=coordX; y=coordY; }

public Point(float xy) { this(xy,xy); }}

Constructor chaining

Page 22: 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:

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

Page 23: 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:

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){ x+=dx; y+=dy; }

public void move(float dxy){ move(dxy, dxy); }}

Page 24: 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:

Strings Strings in Java are objects of class

java.lang.StringJava.lang is a fundamental libraryString has a lot of nice features:

check it out in the java API!

Page 25: 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:

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;

} ...}

Page 26: 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:

Turning objects into Strings

toString()can be invoked implicitllyWhen object is used within String

manipulation operationsPerson assistant=new Person(“Mike”);

System.out.println(“the assistant is: "+ assistant);

Page 27: 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:

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