0% found this document useful (0 votes)
117 views56 pages

Chapter 4 Classes & Objects

This document discusses classes and objects in Java. It explains that an object has state stored in fields and behavior defined by methods. A class defines a new type of object and specifies its fields and methods. Objects are instantiated from classes using the new keyword. Constructors initialize new objects and can be overloaded. Abstraction allows treating objects generically based on their interfaces rather than implementations. Fields and methods can be declared privately to enforce abstraction.

Uploaded by

Moti King Moti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views56 pages

Chapter 4 Classes & Objects

This document discusses classes and objects in Java. It explains that an object has state stored in fields and behavior defined by methods. A class defines a new type of object and specifies its fields and methods. Objects are instantiated from classes using the new keyword. Constructors initialize new objects and can be overloaded. Abstraction allows treating objects generically based on their interfaces rather than implementations. Fields and methods can be declared privately to enforce abstraction.

Uploaded by

Moti King Moti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 56

Chapter 4:

Classes and Objects - Part I

AUHHC oop lecture slides 1


What is an Object?
An Object has two primary components:
◦ state – properties of the object
◦ behavior – operations the object can perform

Examples

object state behavior


dog breed, isHungry eat, bark
grade book grades mean, median
light on/off switch

AUHHC oop lecture slides 2


Objects in Java
A class defines a new type of Object
To create an Object type to represent a light
switch . . .
class LightSwitch {

// state and behavior here

AUHHC oop lecture slides 3


Fields
An Object's state is stored in variables called
fields
Fields are declared (and optionally
initialized) inside the braces of the class
Light switch example with a field . . .

class LightSwitch {

boolean on = true;

} AUHHC oop lecture slides 4


Methods

An Object's behavior is defined by its


methods

Methods, like fields, are written inside the


braces of the class

Methods can access the fields (the state) of


their object and can change them
AUHHC oop lecture slides 5
Light Switch Example
class LightSwitch {

boolean on = true; // field

boolean isOn() { // returns


return on; // the state
}

void switch() { // changes


on = !on; // the state
}
} AUHHC oop lecture slides 6
Constructing Objects
We use the new keyword to construct a new
instance of an Object

We can assign this instance to a variable with


the same type of the Object

LightSwitch ls = new LightSwitch();

Note: classes define new datatypes !


AUHHC oop lecture slides 7
Using Fields and Methods
LightSwitch ls = new LightSwitch();
To access the field of an instance of an Object
use instance.field
ls.on;

Toaccess the method of an instance use


instance.method(arguments)
ls.isOn();
ls.switch();
AUHHC oop lecture slides 8
Example Using Light Switch

What does this main method print out?

LightSwitch ls = new LightSwitch();


System.out.println(ls.on);
ls.switch();
System.out.println(ls.isOn());

true
false
AUHHC oop lecture slides 9
Person Example
class Person {
String name = “Jamal”;
int age = 26;
String getName() {
return name;
}
void setName(String n) {
name = n;
}
int getAge() {
return age;
}
void setAge(int a) {
age = a;
}
boolean smellsBad(){
return true;
}
}
AUHHC oop lecture slides 10
Constructing Person Objects
To create an instance of the Person class with a
name of "George" and an age of 22
Person george = new Person();
george.setName("George");
george.setAge(22);

Can we create a Person that has the name


George and the age 22 from the moment it is
created?
Answer: Yes!
AUHHC oop lecture slides 11
Constructors
Constructors are special methods used to construct
an instance of a class

They have no return type

They have the same name as the class of the Object


they are constructing

They initialize the state of the Object

Callthe constructor by preceding it with the new


keyword AUHHC oop lecture slides 12
Person Constructor
class Person {
String name;
int age;

Person(String n, int a) {
name = n;
age = a;
}

// . . .
}
Now we can construct George as follows:
Person george = new Person("George", 22);
AUHHC oop lecture slides 13
Default Constructor
When you do not write a constructor in a class, it
implicitly has a constructor with no arguments
and an empty body
class LightSwitch {

// Leaving out the constructor


// is the same as . . .
LightSwitch() {}
}
Result: every class has a constructor
AUHHC oop lecture slides 14
Multiple Constructors
A class can have multiple constructors
class LightSwitch {

boolean on;

LightSwitch() {
on = true;
}

LightSwitch(boolean o) {
on = o;
}
} AUHHC oop lecture slides 15
This Keyword
 Instance can refer to itself with the keyword this

class LightSwitch {
boolean on;
LightSwitch() {
this.on = true; //(same as
on=true;)
}

LightSwitch(boolean on) {
this.on = on;
}
}
AUHHC oop lecture slides 16
Cascading Constructors
A constructor
can call another constructor with
this(arguments)
class LightSwitch {

boolean on;

LightSwitch() {
this(true);
}

LightSwitch(boolean on) {
this.on = on;
}
AUHHC oop lecture slides 17
}
Classes Recap
Classes have fields to store the state of the objects
in the class and methods to provide the operations
the objects can perform.
We construct instances of a class with the keyword
new followed by a call a constructor method of the
class.
We can assign an instance to a variable with a
datatype named the same as the class.
If you do not provide a constructor, the class will
have one with no arguments and no statements by
default. AUHHC oop lecture slides 18
Apple Example
class Apple {
String color;
double price;
Apple(String color, double price) {
this.color = color;
this.price = price;
}
Apple(double price) {
this("green", price);
}
String getColor() {
return color;
}
double getPrice() {
return price;
}
void setPrice(double p) {
price = p;
}
}
AUHHC oop lecture slides 19
Apple Quiz
What will these lines print out?
Apple a = new Apple("red", 100.0);
System.out.println(a.getColor());
System.out.println(a.getPrice()); red
a.setPrice(50.5); 100.0
System.out.println(a.getPrice());
Apple b = new Apple(74.6); 50.5
System.out.println(b.getColor());
System.out.println(b.getPrice());
b.setPrice(a.getPrice()); green
System.out.println(b.getPrice()); 74.6

50.5
AUHHC oop lecture slides 20
Recall the LightSwitch Class
class LightSwitch {

boolean on = true;

boolean isOn() {
return on;
}

void switch() {
on = !on;
}
} AUHHC oop lecture slides 21
A Different LightSwitch Class
class LightSwitch {

int on = 1;

boolean isOn() {
return on == 1;
}

void switch() {
on = 1 - on;
}
} AUHHC oop lecture slides 22
Abstraction
Both LightSwitch classes behave the same.
We treat LightSwitch as an abstraction: we do
not care about the internal code of LightSwitch,
only the external behavior

Internalcode = implementation
External behavior = interface

AUHHC oop lecture slides 23


Why is Abstraction Important?

We can continue to refine and improve the


implementation of a class so long as the
interface remains the same.

All we need is the interface to an Object in


order to use it, we do not need to know
anything about how it performs its prescribed
behavior.

AUHHC oop lecture slides 24


Breaking the Abstraction Barrier
A user of LightSwitch that relied on the
boolean field would break if we changed to
an integer field
class AbstractionBreaker {
public static void main(String[] args) {
LightSwitch ls = new LightSwitch();

if (ls.on) // now broken!


System.out.println("light is on");
else
System.out.println("light is off");
}
} AUHHC oop lecture slides 25
Public versus Private

Label fields and methods private to ensure


other classes can't access them

Label fields and methods public to ensure


other classes can access them.

Ifthey are not labeled public or private, for


now consider them public.
AUHHC oop lecture slides 26
A Better LightSwitch
class LightSwitch {

private boolean on = true;

public boolean isOn() {


return on;
}

public void switch() {


on = !on;
}
} AUHHC oop lecture slides 27
Enforcing the Abstraction Barrier
By labeling the on field private . . .
class LightSwitch {
private boolean on = true;

// . . .
}
Now AbstractionBreaker's attempt to access
the on field would not have compiled to begin
with.

if (ls.on) // would never have compiled


AUHHC oop lecture slides 28
Equality Quiz 1
Is (a == b) ?
int a = 7;
int b = 7;
Answer: Yes

Is (g == h) ?
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
Answer: No
AUHHC oop lecture slides 29
Primitives vs Objects
Two datatypes in Java: primitives and objects

Primitives: byte, short, int, long, double, float,


boolean, char
== tests if two primitives have the same value

Objects: defined in Java classes


== tests if two objects are the same object
AUHHC oop lecture slides 30
References
The new keyword always constructs a new
unique instance of a class
When an instance is assigned to a variable,
that variable is said to hold a reference
or point to that object
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
g and h hold references to two different
objects that happen to have identical state
AUHHC oop lecture slides 31
Reference Inequality
g != h because g and h hold references to
different objects
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);

g h

"Jamal" "Jamal"
26 26

AUHHC oop lecture slides 32


Reference Equality
greg1 == greg2 because greg1 and greg2
hold references to the same object
Person greg1 = new Person("Greg", 23);
Person greg2 = greg1;

greg1

"Greg"
23

greg2

AUHHC oop lecture slides 33


Equality Quiz 2
 true or false?
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
Person greg1 = new Person("Greg", 23);
Person greg2 = greg1;

a) g == h false
b) g.getAge() == h.getAge() true
c) greg1 == greg2 true
d) greg1.getAge() == greg2.getAge(); true
AUHHC oop lecture slides 34
Java API
You can get information on all in-built Java
classes/methods by browsing the Java
Application Programming Interface (API)

This documentation is essential to building any


substantial Java application

Available on your CD's


AUHHC oop lecture slides 35
Methods

Methods

AUHHC oop lecture slides 36


The Concept of a Method
Methods also known as functions or procedures.
Methods are a way of capturing a sequence of
computational steps into a reusable unit.
Methods can accept inputs in the form of arguments,
perform some operations with the arguments, and then
can return a value the is the output, or result of their
computations.
inputs outputs
method
AUHHC oop lecture slides 37
Square Root Method
 Square root is a good example of a method.

 The square root method accepts a single number as an argument


and returns the square root of that number.

 The computation of square roots involves many intermediate


steps between input and output.

 When we use square root, we don’t care about these steps. All
we need is to get the correct output.

 Hiding the internal workings of a method from a user but


providing the correct answer is known as abstraction
AUHHC oop lecture slides 38
Declaring Methods
A method has 4 parts: the return type, the name,
the arguments, and the body:
type name arguments

double sqrt(double num) {


// a set of operations that compute
body
// the square root of a number
}

The type, name and arguments together is referred


to as the signature of the method
AUHHC oop lecture slides 39
The Return Type of a Method

The return type of a method may be any


data type.

The type of a method designates the data


type of the output it produces.

Methods can also return nothing in


which case they are declared void.
AUHHC oop lecture slides 40
Return Statements
 The return statement is used in a method to output the result
of the methods computation.

 It has the form: return expression_value;

 The type of the expression_value must be the same as


the type of the method:
double sqrt(double num){
double answer;
// Compute the square root of num and store
// the value into the variable answer
return answer;
} AUHHC oop lecture slides 41
Return Statements

A method exits immediately after it


executes the return statement

Therefore, the return statement is usually


the last statement in a method

A method may have multiple return


statements. Can you think of an example
of such a case?
AUHHC oop lecture slides 42
Brain Teaser Answer

Example:

int absoluteValue (int num){


if (num < 0)
return –num;
else
return num;
}
AUHHC oop lecture slides 43
void Methods

A method of type void has a return statement


without any specified value. i.e. return;

This may seem useless, but in practice void is used


often.

A good example is when a methods only purpose is to


print to the screen.

Ifno return statement is used in a method of type


void, it automatically returns at the end
AUHHC oop lecture slides 44
Method Arguments

Methods can take input in the form of


arguments.

Arguments are used as variables inside the


method body.

Like variables, arguments, must have their type


specified.

Arguments are specified inside the paren-theses


that follow the name of the method.
AUHHC oop lecture slides 45
Example Method

Here is an example of a method that divides


two doubles:

double divide(double a, double b) {


double answer;
answer = a / b;
return answer;
}
AUHHC oop lecture slides 46
Method Arguments

Multiple
method arguments are separated
by commas:
double pow(double x, double y)

Arguments may be of different types


int indexOf(String str, int fromIndex)

AUHHC oop lecture slides 47


The Method Body

The body of a method is a block specified


by curly brackets.
 The body defines the actions of the
method.
The method arguments can be used
anywhere inside of the body.
All methods must have curly brackets to
specify the body even if the body contains
only one or no statement.
AUHHC oop lecture slides 48
Invoking Methods

To call a method, specify the name of the


method followed by a list of comma
separated arguments in parentheses:
pow(2, 10); //Computes 210

Ifthe method has no arguments, you still


need to follow the method name with
empty parentheses:
size();
AUHHC oop lecture slides 49
Static Methods

Some methods have the keyword static


before the return type:
static double divide(double a, double b)
{
return a / b;
}
The keyword static allows main( ) method
for instance to be called without having to
instantiate a particular instance of the class.

AUHHC oop lecture slides 50


main - A Special Method
The only method that we have used in lab up
until this point is the main method.
The main method is where a Java program
always starts when you run a class file with the
java command
The main method is static has a strict signature
which must be followed:
public static void main(String[] args) {
. . .
} AUHHC oop lecture slides 51
main continued
class SayHi {
public static void main(String[] args) {
System.out.println("Hi, " + args[0]);
}
}
 When java Program arg1 arg2 … argN is typed on the
command line, anything after the name of the class file is
automatically entered into the args array:
java SayHi Sonia

 In this example args[0] will contain the String "Sonia", and


the output of the program will be "Hi, Sonia".
AUHHC oop lecture slides 52
Example main method
class Greetings {
public static void main(String args[]) {
String greeting = "";
for (int i=0; i < args.length; i++) {
greeting += "Jambo " + args[i] + "! ";
}
System.out.println(greeting);
}
}

 Aftercompiling, if you type


java Greetings Alice Bob Charlie
prints out "Jambo Alice! Jambo Bob! Jambo Charlie!"

AUHHC oop lecture slides 53


Recursive Example
class Factorial {
public static void main (String[] args) {
int num = Integer.parseInt(args[0]));
System.out.println(fact(num));
}

static int fact(int n) {


if (n <= 1) return 1;
else return n * fact(n – 1);
}
}

 After compiling, if you type java Factorial 4


the program will print out 24
AUHHC oop lecture slides 54
Another Example
class Max {
public static void main(String args[]) {
if (args.length == 0) return;

int max = Integer.parseInt(args[0]);


for (int i=1; i < args.length; i++) {
if (Integer.parseInt(args[i]) > max) {
max = Integer.parseInt(args[i]);
}
}
System.out.println(max);
}
}

 After compiling, if you type java Max 3 2 9 2 4


the program will print out 9
AUHHC oop lecture slides 55
Summary

 Methods capture a piece of computation we wish to


perform repeatedly into a single abstraction
 Methodsin Java have 4 parts: return type, name,
arguments, body.
 The return type and arguments may be either primitive
data types or complex data types (Objects)
 main is a special Java method which the java interpreter
looks for when you try to run a class file
 main has a strict signature that must be followed:
public static void main(String args[])
AUHHC oop lecture slides 56

You might also like