0% found this document useful (0 votes)
22 views35 pages

Week 2 - Lectures 1 and 2 - Chapter 8

Uploaded by

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

Week 2 - Lectures 1 and 2 - Chapter 8

Uploaded by

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

Chapter 8 Objects and Classes

8.2 Defining Classes for Objects


8.3 Example: Defining classes and Creating Objects
8.4 Constructing Objects Using Constructors
8.5 Accessing Objects via Reference Variables

1
8.2 Defining Classes for Objects
What is an object?
Object-oriented programming (OOP) involves
programming using objects. An object represents
an entity in the real world. For example, a student,
a desk, a circle, and even a loan can all be viewed
as objects.
An object has a unique state, and behaviors. The
state of an object consists of a set of data fields
(also known as attributes) with their current values.
The behavior of an object is defined by a set of
2
methods.
8.2 Defining Classes for Objects

What is a class?
Classes are constructs that define objects of the
same type. A Java class uses variables to define
data fields and methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct objects from the class.

3
8.2 Defining Classes for Objects

• A class defines the attributes and behaviors for objects.

• The state of an object (also known as attributes) is


represented by data fields with their current values. A
circle object, for example, has a data field radius, which is
the property that characterizes a circle (See slide 7).

• The behavior of an object (also known as its actions) is


defined by methods. To invoke a method on an object is to
ask the object to perform an action. For example, you may
define a method named getArea() for circle objects (See
slide 7). A circle object may invoke getArea() to return its
area.
4

Classes and Objects
Objects of the same type are defined using a common class.
A class is a template, or blueprint, that defines what an
object’s data fields and methods will be.

• An object is an instance of a class. You can create many


instances of a class. Creating an instance is referred to as
instantiation.

• The relationship between classes and objects is analogous


to that between an apple-pie recipe and apple pies: You can
make as many apple pies as you want from a single recipe.
5
The
public class Circle {
Circle Class Example
double radius ; // attribute (data field)
public Circle(double r) { // A special behavior (method) called the
// constructor used to create a circle object
radius = r; // initialize the data field to the value of the parameter r
}
public double getArea( ) { // behavior (method) to return the area
return radius * radius * Math.PI; // Math.PI is a constant =3.14159
}
} // end class Circle
6
UML Class Diagram

UML Class Diagram Circle Class name

radius: double Data fields

Circle() Constructors and


Circle(newRadius: double) methods
getArea(): double

circle2: Circle circle3: Circle UML notation


circle1: Circle
for objects
radius = 1.0 radius = 25 radius = 125

7
8.3 Example: Defining Classes
and Creating Objects

• Classes are definitions for objects and objects are


created from classes.

• We will rewrite the class Circle and add two new


methods: A second constructor that initializes the
radius to a default value 1 and a method
getPerimeter which returns the perimeter of the
circle.
8
The Circle Class Revisited
public class Circle {
double radius ; // attribute (data field)
public Circle( ) { // Constructor 1 – Has no parameters
radius = 1; // initialize radius to a default value 1
}
public Circle(double newRadius) { // Constructor 2
radius = newRadius; // initialize radius to parameter value
}
public double getArea( ) { // behavior (method) to return the area of the circle
return Math.PI * radius * radius;
}
public double getPerimeter( ) { // behavior (method) to return the perimeter
return 2 * Math.PI * radius;
}
} // end class Circle 9
8.3 Defining classes and Creating Objects

• We have learned how to define (write) a class. Now we want to see


how we can create objects using the class Circle found in the
previous slide. We also want to learn how to call /invoke a method
(behavior) from the class Circle using the object created.

• Note that usually we create objects in an application in the main


method or in other methods. Also, usually we create two java files
one for the class and one for the application.

10

Creating an object
We create a circle object using one the following two
statements:
Circle circle1 = new Circle();
Circle circle2 = new Circle(25);
• Where Circle which is the class name is also known as the
type (reference type), circle1 is the variable (a.k.a. object
reference variable), new is a keyword, and Circle () /
Circle(25) is a call to the constructor.

11
Creating an object (continued)
Circle circle1 = new Circle(25);

In the above statement the keyword new is


responsible for creating a new Circle object and
Circle(25) is a call to the constructor that has
newRadius as a parameter in its header while passing
the argument 25. The value 25 will be used by the
constructor to initialize the data field radius. The
equal sign will make the object reference circle1 refer
to the created object. We can think of circle1 as the
12
name of the object.
Creating an object (continued)
Circle circle1 = new Circle();

The difference between the above statement and the


one in the previous slide is that the constructor with
no parameters (also know as the No-Arg constructor)
is called and it will initialize the radius to the default
value 1.

13
Example Application
public class Application {
public static void main(String[] args) {
Circle circle1 = new Circle(); // Create a circle with radius 1
// print the area of circle 1
System.out.println("The area is " + circle1. getArea() );
Circle circle2 = new Circle(25); // Create a circle with radius 25
// print the area of circle 2
System.out.println("The area is " + circle2. getArea() );
// print the perimeter of circle 2
System.out.println("The perimeter is " + circle2. getPerimeter() );
}
14
}
8.4 Constructing Objects Using
Constructors
Constructors are a special kind of methods that are
invoked to construct objects.
public Circle() { // No-arg constructor
radius =1;
}

// Constructor with arguments


public Circle(double newRadius) {
radius = newRadius;
15
}
Constructors (continued)
• Constructors must have the same name as the class
itself.
• Constructors do not have a return type—not even
void.
• Constructors are invoked/called using the new
operator when an object is created. Constructors
play the role of initializing objects.
• A constructor with no parameters is referred to as a
no-arg constructor.
16
Default Constructor
A class may be declared without constructors. In
this case, a no-arg constructor with an empty body
is implicitly declared in the class. This constructor,
called a default constructor, is provided
automatically only if no constructors are explicitly
declared in the class.

17
8.5 Accessing Objects via Reference Variables
Types

8.5.1 Reference Variables and Reference


To reference (access) an object, we use a reference variable.

To declare a reference variable, use the syntax:


ClassName objectRefVar;
Example:
Circle myCircle; // declaration statement
Where, Circle is called the class name, the reference type, or simply
the type and myCircle is called the object’s reference variable, the
reference variable, the object reference , or simply the reference.
18
Declaring and Creating Objects in a
Single Step:

ClassName objectRefVar = new ClassName();

Assign object reference Create an object


Example:
Circle myCircle = new Circle();
The other way is to write:
Circle myCircle; // declaration statement
myCircle = new Circle(); // creation statement 19
8.5.2 Accessing an Object’s Data and
Methods
• To Reference the object’s data we use the dot
operator between the reference and the data field:
objectRefVar.data
e.g., myCircle.radius

• To invoke/call an object’s method we use the dot


operator between the reference and the method:
objectRefVar.methodName(arguments)
e.g., myCircle.getArea() 20
animation
Trace Code
Declare myCircle

Circle myCircle = new Circle(5.0); no value


myCircle
SCircle yourCircle = new Circle();

yourCircle.radius = 100;

21
animation
Trace Code, cont.

Circle myCircle = new Circle(5.0); no value


myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

Create a circle

22
animation
Trace Code, cont.

Circle myCircle = new Circle(5.0); reference value


myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; Assign object reference : Circle


to myCircle
radius: 5.0

23
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

Declare yourCircle

24
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

: Circle
Create a new
Circle object radius: 1.0

25
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

Assign object reference


to yourCircle : Circle

radius: 1.0

26
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

: Circle
Change radius in
radius: 100.0
yourCircle

27
Caution

Recall that you use


Math.methodName(arguments) (e.g., Math.pow(3, 2))
to call/invoke a method in the Math class (a class found in the library).

Can you invoke getArea() using Circle.getArea()? The answer is no. All
the methods used before this chapter are static methods, which are
defined using the static keyword. However, getArea() is non-static. It
must be invoked from an object using

objectRefVar.methodName(arguments) (e.g., myCircle.getArea()).

More explanations will be given later in section 8.7 “Static Variables,


Constants, and Methods.”
28
8.5.3 Reference Data Fields and the
null Value
The data fields can be of reference types. For example,
the following Student class contains a data field name of
the String type (String is a class found in the library).
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // c has default value '\u0000'
}

29
The null Value

• If a data field of a reference type (such as


String) does not reference any object, the
data field holds a special value, null.

• Hence null is the default value for any data


field of a reference type.

• Note that null is a keyword in Java.


30
Default Value for a Data Field
The default value of a data field is null for a reference type,
0 for a numeric type, false for a boolean type, and '\u0000'
for a char type ('\u0000' is equivalent to null) .

Try running the code below after writing the class Student.
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " + student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
31
Caution
Java assigns no default value to a local variable
inside a method. As discussed earlier, Java only
assigns default values to data fields in a class.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}

Compilation error: variables not


initialized 32
8.5.4 Differences between Variables of Primitive Types and
Reference Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle

radius = 1

33
Copying Variables of Primitive Data
Types and Reference Types
Primitive type assignment i = j

Before: After:

i 1 i 2

j 2 j 2

Object type assignment c1 = c2

Before: After:

c1 c1

c2 c2

c1: Circle c2: Circle c1: Circle c2: Circle


radius = 5 radius = 9 radius = 5 34 radius = 9
Garbage Collection
As shown in the previous figure, after the assignment statement
c1 = c2, c1 points to the same object referenced by c2. The
object previously referenced by c1 is no longer referenced. This
object is known as garbage. Garbage in memory is
automatically collected by JVM.

You are always advised to read the sections in your book.


This presentation is just a summary of the important points
in the sections.

35

You might also like