SlideShare a Scribd company logo
Chapter 4
Objects and Classes
Object variables
data field 1
method n
data field n
method 1
An object
...
...
State
Behavior
Data Field
radius = 5
Method
findArea
A Circle object
Class and Objects
circle1: Circle
radius = 2
new Circle()
circlen: Circle
radius = 5
new Circle()
...
UML Graphical notation for classes
UML Graphical notation
for objects
Circle
radius: double
findArea(): double
UML Graphical notation for fields
UML Graphical notation for methods
4
Defining a class
• Class provides one or more methods
• Method represents task in a program
– Describes the mechanisms that actually perform
its tasks
– Hides from its user the complex tasks that it
performs
– Method call tells method to perform its task
5
Defining a class
• Classes contain one or more attributes
– Specified by instance variables
– Carried with the object as it is used
6
Defining a class
• Each class declaration that begins with
keyword public must be stored in a file
that has the same name as the class and
ends with the .java file-name extension.
7
Class GradeBook
• keyword public is an access modifier
• Class declarations include:
– Access modifier
– Keyword class
– Pair of left and right braces
8
Class GradeBook
• Method declarations
– Keyword public indicates method is
available to public
– Keyword void indicates no return type
– Access modifier, return type, name of method
and parentheses comprise method header
9
• GradeBook.java
1 // Fig. 3.1: GradeBook.java
2 // Class declaration with one method.
3
4 public class GradeBook
5 {
6 // display a welcome message to the GradeBook user
7 public void displayMessage()
8 {
9 System.out.println( "Welcome to the Grade Book!" );
10 } // end method displayMessage
11
12 } // end class GradeBook
Print line of text to output
10
Outline
• GradeBookTest.java
1 // Fig. 3.2: GradeBookTest.java
2 // Create a GradeBook object and call its displayMessage method.
3
4 public class GradeBookTest
5 {
6 // main method begins program execution
7 public static void main( String args[] )
8 {
9 // create a GradeBook object and assign it to myGradeBook
10 GradeBook myGradeBook = new GradeBook();
11
12 // call myGradeBook's displayMessage method
13 myGradeBook.displayMessage();
14 } // end main
15
16 } // end class GradeBookTest
Welcome to the Grade Book!
Use class instance creation
expression to create object of
class GradeBook
Call method
displayMessage using
GradeBook object
Class Declaration
class Circle {
double radius = 1.0;
double findArea(){
return radius * radius * 3.14159;
}
}
Declaring Object Reference Variables
ClassName objectReference;
Example:
Circle myCircle;
Creating Objects
objectReference = new ClassName();
Example:
myCircle = new Circle();
The object reference is assigned to the object
reference variable.
Declaring/Creating Objects
in a Single Step
ClassName objectReference = new ClassName();
Example:
Circle myCircle = new Circle();
15
Primitive Types vs. Reference Types
• Types in Java
– Primitive
• boolean, byte, char, short, int, long,
float, double
– Reference (sometimes called nonprimitive
types)
• Objects
• Default value of null
• Used to invoke an object’s methods
Differences between variables of
primitive Data types and object types
1
c: Circle
radius = 1
Primitive type int i = 1 i
Object type Circle c c reference
Created using
new Circle()
Copying Variables of Primitive Data
Types and Object Types
1
c1: Circle
radius = 5
Primitive type assignment
i = j
Before:
i
2j
2
After:
i
2j
Object type assignment
c1 = c2
Before:
c1
c2
After:
c1
c2
c2: Circle
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
useful. This object is known
as garbage. Garbage is
automatically collected by
JVM.
Garbage Collection, cont
TIP: If you know that an
object is no longer needed,
you can explicitly assign
null to a reference
variable for the object.
The Java VM will
automatically collect the
space if the object is not
referenced by any variable.
Accessing Objects
• Referencing the object’s data:
objectReference.data
myCircle.radius
• Invoking the object’s method:
objectReference.method
myCircle.findArea()
21
Class GradeBookTest
• Java is extensible
– Programmers can create new classes
• Class instance creation expression
– Keyword new
– Then name of class to create and parentheses
• Calling a method
– Object name, then dot separator (.)
– Then method name and parentheses
22
Compiling an Application with Multiple Classes
• Compiling multiple classes
– List each .java file separately separated with
spaces
– Compile with *.java to compile all .java
files in that directory
23
Initializing Objects with Constructors
• Constructors
– Initialize an object of a class
– Java requires a constructor for every class
– Java will provide a default no-argument
constructor if none is provided
– Called when keyword new is followed by the
class name and parentheses
Constructors
Circle(double r) {
radius = r;
}
Circle() {
radius = 1.0;
}
myCircle = new Circle(5.0);
Constructors are a
special kind of
methods that are
invoked to construct
objects.
Constructors, cont.
• A constructor with no parameters is
referred to as a default constructor.
• Constructors must have the same name
as the class itself.
• Constructors do not have a return
type—not even void.
• Constructors are invoked using the
new operator when an object is
created. Constructors play the role
of initializing objects.
26
Outline
• GradeBook.jav
a
• (1 of 2)
1 // Fig. 3.10: GradeBook.java
2 // GradeBook class with a constructor to initialize the course name.
3
4 public class GradeBook
5 {
6 private String courseName; // course name for this GradeBook
7
8 // constructor initializes courseName with String supplied as argument
9 public GradeBook( String name )
10 {
11 courseName = name; // initializes courseName
12 } // end constructor
13
14 // method to set the course name
15 public void setCourseName( String name )
16 {
17 courseName = name; // store the course name
18 } // end method setCourseName
19
20 // method to retrieve the course name
21 public String getCourseName()
22 {
23 return courseName;
24 } // end method getCourseName
Constructor to initialize
courseName variable
27
Instance Variables, set Methods and get
Methods
• Variables declared in the body of method
– Called local variables
– Can only be used within that method
• Variables declared in a class declaration
– Called fields or instance variables
– Each object of the class has a separate
instance of the variable
28
Outline
• GradeBook.java
1 // Fig. 3.7: GradeBook.java
2 // GradeBook class that contains a courseName instance variable
3 // and methods to set and get its value.
4
5 public class GradeBook
6 {
7 private String courseName; // course name for this GradeBook
8
9 // method to set the course name
10 public void setCourseName( String name )
11 {
12 courseName = name; // store the course name
13 } // end method setCourseName
14
15 // method to retrieve the course name
16 public String getCourseName()
17 {
18 return courseName;
19 } // end method getCourseName
20
21 // display a welcome message to the GradeBook user
22 public void displayMessage()
23 {
24 // this statement calls getCourseName to get the
25 // name of the course this GradeBook represents
26 System.out.printf( "Welcome to the grade book forn%s!n",
27 getCourseName() );
28 } // end method displayMessage
29
30 } // end class GradeBook
Instance variable
courseName
set method for courseName
get method for courseName
Call get method
29
Access Modifiers public and private
• private keyword
– Used for most instance variables
– private variables and methods are
accessible only to methods of the class in
which they are declared
– Declaring instance variables private is
known as data hiding
• Return type
– Indicates item returned by method
– Declared in method header
30
set and get methods
• private instance variables
– Cannot be accessed directly by clients of the
object
– Use set methods to alter the value
– Use get methods to retrieve the value
31
Outline
• GradeBookTes
t.java
• (1 of 2)
1 // Fig. 3.8: GradeBookTest.java
2 // Create and manipulate a GradeBook object.
3 import java.util.Scanner; // program uses Scanner
4
5 public class GradeBookTest
6 {
7 // main method begins program execution
8 public static void main( String args[] )
9 {
10 // create Scanner to obtain input from command window
11 Scanner input = new Scanner( System.in );
12
13 // create a GradeBook object and assign it to myGradeBook
14 GradeBook myGradeBook = new GradeBook();
15
16 // display initial value of courseName
17 System.out.printf( "Initial course name is: %snn",
18 myGradeBook.getCourseName() );
19
Call get method for
courseName
32
Outline
• GradeBookTes
t.java
• (2 of 2)
20 // prompt for and read course name
21 System.out.println( "Please enter the course name:" );
22 String theName = input.nextLine(); // read a line of text
23 myGradeBook.setCourseName( theName ); // set the course name
24 System.out.println(); // outputs a blank line
25
26 // display welcome message after specifying course name
27 myGradeBook.displayMessage();
28 } // end main
29
30 } // end class GradeBookTest
Initial course name is: null
Please enter the course name:
CS101 Introduction to Java Programming
Welcome to the grade book for
CS101 Introduction to Java Programming!
Call set method for
courseName
Call displayMessage
Visibility Modifiers and
Accessor Methods
By default, the class, variable, or data can be
accessed by any class in the same package.
 public
The class, data, or method is visible to any class in any
package.
 private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
Passing Objects to Methods, cont.
main
method
ReferencemyCircle
5n 5
times
printAreas
method
Reference
c
myCircle: Circle
radius = 1
Pass by value (here the value is 5)
Pass by value (here the value is the
reference for the object)
Instance
Variables, and Methods
Instance variables belong to a specific instance.
Instance methods are invoked by an instance of
the class.
Class Variables, Constants,
and Methods
Class variables are shared by all the instances of the
class.
Class methods are not tied to a specific object.
Class constants are final variables shared by all the
instances of the class.
Class Variables, Constants,
and Methods, cont.
To declare class variables, constants, and methods,
use the static modifier.
Class Variables, Constants,
and Methods, cont.
CircleWithStaticVariable
-radius
-numOfObjects
+getRadius(): double
+setRadius(radius: double): void
+getNumOfObjects(): int
+findArea(): double
1 radiuscircle1:Circle
-radius = 1
-numOfObjects = 2
instantiate
instantiate
Memory
2
5 radius
numOfObjects
radius is an instance
variable, and
numOfObjects is a
class variable
UML Notation:
+: public variables or methods
-: private variables or methods
underline: static variables or metods
circle2:Circle
-radius = 5
-numOfObjects = 2
Scope of Variables
• The scope of instance and class variables is the
entire class. They can be declared anywhere
inside a class.
• The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must
be declared before it can be used.
The Keyword this
• Use this to refer to the current object.
• Use this to invoke other constructors of the
object.
Array of Objects
Circle[] circleArray = new
Circle[10];
An array of objects is actually
an array of reference variables.
So invoking
circleArray[1].findArea()
involves two levels of
referencing as shown in the next
figure. circleArray references to
the entire array. circleArray[1]
references to a Circle object.
Array of Objects, cont.
reference Circle object 0circleArray[0]
…
circleArray
circleArray[1]
circleArray[9] Circle object 9
Circle object 1
Circle[] circleArray = new
Circle[10];
Class Abstraction
• Class abstraction means to separate class
implementation from the use of the class.
• The creator of the class provides a description
of the class and let the user know how the class
can be used. The user of the class does not need
to know how the class is implemented. The
detail of implementation is encapsulated and
hidden from the user.
Java API and Core Java classes
• java.lang
Contains core Java classes, such as numeric
classes, strings, and objects. This package is
implicitly imported to every Java program.
• java.awt
Contains classes for graphics.
• java.applet
Contains classes for supporting applets.
• java.io
Contains classes for input and output
streams and files.
• java.util
Contains many utilities, such as date.
• java.net
Contains classes for supporting
network communications.
Java API and Core Java classes, cont.
• java.awt.image
Contains classes for managing bitmap images.
• java.awt.peer
Platform-specific GUI implementation.
• Others:
java.sql
java.rmi
Java API and Core Java classes, cont.

More Related Content

PPTX
Java chapter 5
Abdii Rashid
 
PDF
ITFT-Classes and object in java
Atul Sehdev
 
PDF
Lect 1-java object-classes
Fajar Baskoro
 
PPT
Lect 1-class and object
Fajar Baskoro
 
PPT
Object and class
mohit tripathi
 
PPTX
Class or Object
Rahul Bathri
 
PPTX
Java class,object,method introduction
Sohanur63
 
PDF
Classes and objects in java
Muthukumaran Subramanian
 
Java chapter 5
Abdii Rashid
 
ITFT-Classes and object in java
Atul Sehdev
 
Lect 1-java object-classes
Fajar Baskoro
 
Lect 1-class and object
Fajar Baskoro
 
Object and class
mohit tripathi
 
Class or Object
Rahul Bathri
 
Java class,object,method introduction
Sohanur63
 
Classes and objects in java
Muthukumaran Subramanian
 

What's hot (20)

PPTX
Classes and objects
rajveer_Pannu
 
PPT
4 Classes & Objects
Praveen M Jigajinni
 
PDF
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
PDF
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
PPTX
Classes and objects
Shailendra Veeru
 
PPS
Introduction to class in java
kamal kotecha
 
PPTX
C++ classes
Aayush Patel
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPT
Class and object in C++
rprajat007
 
PDF
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
PPTX
C++ And Object in lecture3
UniSoftCorner Pvt Ltd India.
 
PDF
Class and object in C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 
PPTX
Class introduction in java
yugandhar vadlamudi
 
PDF
Java Methods
Rosmina Joy Cabauatan
 
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
PDF
How to write you first class in c++ object oriented programming
Syed Faizan Hassan
 
PDF
Class and Objects in Java
Spotle.ai
 
PPT
Object and Classes in Java
backdoor
 
PPT
Object and class in java
Umamaheshwariv1
 
PPT
Class and object in c++
NainaKhan28
 
Classes and objects
rajveer_Pannu
 
4 Classes & Objects
Praveen M Jigajinni
 
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
Classes and objects
Shailendra Veeru
 
Introduction to class in java
kamal kotecha
 
C++ classes
Aayush Patel
 
Classes, objects in JAVA
Abhilash Nair
 
Class and object in C++
rprajat007
 
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
C++ And Object in lecture3
UniSoftCorner Pvt Ltd India.
 
Class and object in C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 
Class introduction in java
yugandhar vadlamudi
 
Java Methods
Rosmina Joy Cabauatan
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
How to write you first class in c++ object oriented programming
Syed Faizan Hassan
 
Class and Objects in Java
Spotle.ai
 
Object and Classes in Java
backdoor
 
Object and class in java
Umamaheshwariv1
 
Class and object in c++
NainaKhan28
 
Ad

Similar to Java chapter 4 (20)

PPT
Lecture 2 classes i
the_wumberlog
 
PPT
Core Java unit no. 1 object and class ppt
Mochi263119
 
PPT
Module 3 Class and Object.ppt
RanjithKumar742256
 
PPTX
Class and Object.pptx
Hailsh
 
PPT
packages and interfaces
madhavi patil
 
PPTX
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Blue Elephant Consulting
 
PPT
Java Presentation.ppt
Morgan309846
 
PPTX
Lecture 5
talha ijaz
 
PDF
Chapter3 bag2
teknik komputer ui
 
PPTX
Unit3 part1-class
DevaKumari Vijay
 
PPTX
Java basics
Shivanshu Purwar
 
PPTX
Lecture 4
talha ijaz
 
PDF
Lecture 1 - Objects and classes
Syed Afaq Shah MACS CP
 
PPT
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
PPT
Class and Object.ppt
Genta Sahuri
 
PPT
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
PPT
Java căn bản - Chapter4
Vince Vo
 
PPT
Ap Power Point Chpt4
dplunkett
 
PPTX
03 Java Language And OOP Part III
Hari Christian
 
PPT
Java sem i
priyankabarhate1
 
Lecture 2 classes i
the_wumberlog
 
Core Java unit no. 1 object and class ppt
Mochi263119
 
Module 3 Class and Object.ppt
RanjithKumar742256
 
Class and Object.pptx
Hailsh
 
packages and interfaces
madhavi patil
 
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Blue Elephant Consulting
 
Java Presentation.ppt
Morgan309846
 
Lecture 5
talha ijaz
 
Chapter3 bag2
teknik komputer ui
 
Unit3 part1-class
DevaKumari Vijay
 
Java basics
Shivanshu Purwar
 
Lecture 4
talha ijaz
 
Lecture 1 - Objects and classes
Syed Afaq Shah MACS CP
 
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
Class and Object.ppt
Genta Sahuri
 
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Java căn bản - Chapter4
Vince Vo
 
Ap Power Point Chpt4
dplunkett
 
03 Java Language And OOP Part III
Hari Christian
 
Java sem i
priyankabarhate1
 
Ad

More from Abdii Rashid (9)

PPTX
Java chapter 7
Abdii Rashid
 
PPTX
Java chapter 6
Abdii Rashid
 
PPTX
Java chapter 3
Abdii Rashid
 
PPTX
Java chapter 2
Abdii Rashid
 
PPTX
object oriented programming examples
Abdii Rashid
 
PPTX
object oriented programming examples
Abdii Rashid
 
PDF
Chapter 8 advanced sorting and hashing for print
Abdii Rashid
 
PDF
Chapter 7 graphs
Abdii Rashid
 
PPTX
Chapter 1 introduction haramaya
Abdii Rashid
 
Java chapter 7
Abdii Rashid
 
Java chapter 6
Abdii Rashid
 
Java chapter 3
Abdii Rashid
 
Java chapter 2
Abdii Rashid
 
object oriented programming examples
Abdii Rashid
 
object oriented programming examples
Abdii Rashid
 
Chapter 8 advanced sorting and hashing for print
Abdii Rashid
 
Chapter 7 graphs
Abdii Rashid
 
Chapter 1 introduction haramaya
Abdii Rashid
 

Recently uploaded (20)

PPTX
Nitrogen deficiency in plants final.pptx
nasath17mn
 
PDF
2025 MyRWA Wicked Cool Mystic Newsletter.pdf
dariaclark1
 
PPTX
Session 9: Panel 1 - Subramanian Sevgan, International Center for Insect Phys...
ipcc-media
 
PPTX
Oil & Gas Laboratory Services Saudi Arabia.pptx
ETLCO
 
PDF
Topic-5-Human-Dignity-and-Rights-PPT.pdf
johnvlademierlumacan
 
DOCX
Finished Fuel Storage Dependable Welded Steel Tanks.docx
AllenLin596164
 
DOCX
Light Fuel Oil Storage Reliable Welded Steel Tanks.docx
AllenLin596164
 
PDF
cbam presentation.pdf_for exporters exporting tpo Europe
shatrughansingh50
 
PDF
OECD Green Talks LIVE | Securing a sustainable plastics future for Southeast ...
OECD Environment
 
PPTX
carbon footprint, emissioncontrol and carbon tax
DineshKumar11354
 
PPTX
Session 7 - Working Group II - Impacts, Adaptation and Vulnerability
ipcc-media
 
PPTX
challenges and limitations in biofertilizers .pptx
monica892695
 
PPTX
IDA Assignment on natural and envirenmental calamities
naikshreya88
 
PPTX
Session 8a - Sixth Assessment Report Findings
ipcc-media
 
PPTX
DEFENSE MECH AND HOST RESPonse to plaquetx
Sandhya Gnanasambandam
 
PPTX
microbial products for enironment xenobiotics and bioremediation.pptx
monica892695
 
PPT
Hazardous waste handling. Identify hazardous waste.
NasimAhmedMazumder1
 
PPTX
Session 6 - Highlights on progress of the Special Report on Climate Change an...
ipcc-media
 
DOCX
Epoxy Coated Tanks for Wastewater Storage Reliable Effluent Containment.docx
AllenLin596164
 
PPTX
Session 7 - Working Group I - The Physical Science Basis of Climate Change
ipcc-media
 
Nitrogen deficiency in plants final.pptx
nasath17mn
 
2025 MyRWA Wicked Cool Mystic Newsletter.pdf
dariaclark1
 
Session 9: Panel 1 - Subramanian Sevgan, International Center for Insect Phys...
ipcc-media
 
Oil & Gas Laboratory Services Saudi Arabia.pptx
ETLCO
 
Topic-5-Human-Dignity-and-Rights-PPT.pdf
johnvlademierlumacan
 
Finished Fuel Storage Dependable Welded Steel Tanks.docx
AllenLin596164
 
Light Fuel Oil Storage Reliable Welded Steel Tanks.docx
AllenLin596164
 
cbam presentation.pdf_for exporters exporting tpo Europe
shatrughansingh50
 
OECD Green Talks LIVE | Securing a sustainable plastics future for Southeast ...
OECD Environment
 
carbon footprint, emissioncontrol and carbon tax
DineshKumar11354
 
Session 7 - Working Group II - Impacts, Adaptation and Vulnerability
ipcc-media
 
challenges and limitations in biofertilizers .pptx
monica892695
 
IDA Assignment on natural and envirenmental calamities
naikshreya88
 
Session 8a - Sixth Assessment Report Findings
ipcc-media
 
DEFENSE MECH AND HOST RESPonse to plaquetx
Sandhya Gnanasambandam
 
microbial products for enironment xenobiotics and bioremediation.pptx
monica892695
 
Hazardous waste handling. Identify hazardous waste.
NasimAhmedMazumder1
 
Session 6 - Highlights on progress of the Special Report on Climate Change an...
ipcc-media
 
Epoxy Coated Tanks for Wastewater Storage Reliable Effluent Containment.docx
AllenLin596164
 
Session 7 - Working Group I - The Physical Science Basis of Climate Change
ipcc-media
 

Java chapter 4

  • 2. Object variables data field 1 method n data field n method 1 An object ... ... State Behavior Data Field radius = 5 Method findArea A Circle object
  • 3. Class and Objects circle1: Circle radius = 2 new Circle() circlen: Circle radius = 5 new Circle() ... UML Graphical notation for classes UML Graphical notation for objects Circle radius: double findArea(): double UML Graphical notation for fields UML Graphical notation for methods
  • 4. 4 Defining a class • Class provides one or more methods • Method represents task in a program – Describes the mechanisms that actually perform its tasks – Hides from its user the complex tasks that it performs – Method call tells method to perform its task
  • 5. 5 Defining a class • Classes contain one or more attributes – Specified by instance variables – Carried with the object as it is used
  • 6. 6 Defining a class • Each class declaration that begins with keyword public must be stored in a file that has the same name as the class and ends with the .java file-name extension.
  • 7. 7 Class GradeBook • keyword public is an access modifier • Class declarations include: – Access modifier – Keyword class – Pair of left and right braces
  • 8. 8 Class GradeBook • Method declarations – Keyword public indicates method is available to public – Keyword void indicates no return type – Access modifier, return type, name of method and parentheses comprise method header
  • 9. 9 • GradeBook.java 1 // Fig. 3.1: GradeBook.java 2 // Class declaration with one method. 3 4 public class GradeBook 5 { 6 // display a welcome message to the GradeBook user 7 public void displayMessage() 8 { 9 System.out.println( "Welcome to the Grade Book!" ); 10 } // end method displayMessage 11 12 } // end class GradeBook Print line of text to output
  • 10. 10 Outline • GradeBookTest.java 1 // Fig. 3.2: GradeBookTest.java 2 // Create a GradeBook object and call its displayMessage method. 3 4 public class GradeBookTest 5 { 6 // main method begins program execution 7 public static void main( String args[] ) 8 { 9 // create a GradeBook object and assign it to myGradeBook 10 GradeBook myGradeBook = new GradeBook(); 11 12 // call myGradeBook's displayMessage method 13 myGradeBook.displayMessage(); 14 } // end main 15 16 } // end class GradeBookTest Welcome to the Grade Book! Use class instance creation expression to create object of class GradeBook Call method displayMessage using GradeBook object
  • 11. Class Declaration class Circle { double radius = 1.0; double findArea(){ return radius * radius * 3.14159; } }
  • 12. Declaring Object Reference Variables ClassName objectReference; Example: Circle myCircle;
  • 13. Creating Objects objectReference = new ClassName(); Example: myCircle = new Circle(); The object reference is assigned to the object reference variable.
  • 14. Declaring/Creating Objects in a Single Step ClassName objectReference = new ClassName(); Example: Circle myCircle = new Circle();
  • 15. 15 Primitive Types vs. Reference Types • Types in Java – Primitive • boolean, byte, char, short, int, long, float, double – Reference (sometimes called nonprimitive types) • Objects • Default value of null • Used to invoke an object’s methods
  • 16. Differences between variables of primitive Data types and object types 1 c: Circle radius = 1 Primitive type int i = 1 i Object type Circle c c reference Created using new Circle()
  • 17. Copying Variables of Primitive Data Types and Object Types 1 c1: Circle radius = 5 Primitive type assignment i = j Before: i 2j 2 After: i 2j Object type assignment c1 = c2 Before: c1 c2 After: c1 c2 c2: Circle radius = 9
  • 18. 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 useful. This object is known as garbage. Garbage is automatically collected by JVM.
  • 19. Garbage Collection, cont TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The Java VM will automatically collect the space if the object is not referenced by any variable.
  • 20. Accessing Objects • Referencing the object’s data: objectReference.data myCircle.radius • Invoking the object’s method: objectReference.method myCircle.findArea()
  • 21. 21 Class GradeBookTest • Java is extensible – Programmers can create new classes • Class instance creation expression – Keyword new – Then name of class to create and parentheses • Calling a method – Object name, then dot separator (.) – Then method name and parentheses
  • 22. 22 Compiling an Application with Multiple Classes • Compiling multiple classes – List each .java file separately separated with spaces – Compile with *.java to compile all .java files in that directory
  • 23. 23 Initializing Objects with Constructors • Constructors – Initialize an object of a class – Java requires a constructor for every class – Java will provide a default no-argument constructor if none is provided – Called when keyword new is followed by the class name and parentheses
  • 24. Constructors Circle(double r) { radius = r; } Circle() { radius = 1.0; } myCircle = new Circle(5.0); Constructors are a special kind of methods that are invoked to construct objects.
  • 25. Constructors, cont. • A constructor with no parameters is referred to as a default constructor. • Constructors must have the same name as the class itself. • Constructors do not have a return type—not even void. • Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.
  • 26. 26 Outline • GradeBook.jav a • (1 of 2) 1 // Fig. 3.10: GradeBook.java 2 // GradeBook class with a constructor to initialize the course name. 3 4 public class GradeBook 5 { 6 private String courseName; // course name for this GradeBook 7 8 // constructor initializes courseName with String supplied as argument 9 public GradeBook( String name ) 10 { 11 courseName = name; // initializes courseName 12 } // end constructor 13 14 // method to set the course name 15 public void setCourseName( String name ) 16 { 17 courseName = name; // store the course name 18 } // end method setCourseName 19 20 // method to retrieve the course name 21 public String getCourseName() 22 { 23 return courseName; 24 } // end method getCourseName Constructor to initialize courseName variable
  • 27. 27 Instance Variables, set Methods and get Methods • Variables declared in the body of method – Called local variables – Can only be used within that method • Variables declared in a class declaration – Called fields or instance variables – Each object of the class has a separate instance of the variable
  • 28. 28 Outline • GradeBook.java 1 // Fig. 3.7: GradeBook.java 2 // GradeBook class that contains a courseName instance variable 3 // and methods to set and get its value. 4 5 public class GradeBook 6 { 7 private String courseName; // course name for this GradeBook 8 9 // method to set the course name 10 public void setCourseName( String name ) 11 { 12 courseName = name; // store the course name 13 } // end method setCourseName 14 15 // method to retrieve the course name 16 public String getCourseName() 17 { 18 return courseName; 19 } // end method getCourseName 20 21 // display a welcome message to the GradeBook user 22 public void displayMessage() 23 { 24 // this statement calls getCourseName to get the 25 // name of the course this GradeBook represents 26 System.out.printf( "Welcome to the grade book forn%s!n", 27 getCourseName() ); 28 } // end method displayMessage 29 30 } // end class GradeBook Instance variable courseName set method for courseName get method for courseName Call get method
  • 29. 29 Access Modifiers public and private • private keyword – Used for most instance variables – private variables and methods are accessible only to methods of the class in which they are declared – Declaring instance variables private is known as data hiding • Return type – Indicates item returned by method – Declared in method header
  • 30. 30 set and get methods • private instance variables – Cannot be accessed directly by clients of the object – Use set methods to alter the value – Use get methods to retrieve the value
  • 31. 31 Outline • GradeBookTes t.java • (1 of 2) 1 // Fig. 3.8: GradeBookTest.java 2 // Create and manipulate a GradeBook object. 3 import java.util.Scanner; // program uses Scanner 4 5 public class GradeBookTest 6 { 7 // main method begins program execution 8 public static void main( String args[] ) 9 { 10 // create Scanner to obtain input from command window 11 Scanner input = new Scanner( System.in ); 12 13 // create a GradeBook object and assign it to myGradeBook 14 GradeBook myGradeBook = new GradeBook(); 15 16 // display initial value of courseName 17 System.out.printf( "Initial course name is: %snn", 18 myGradeBook.getCourseName() ); 19 Call get method for courseName
  • 32. 32 Outline • GradeBookTes t.java • (2 of 2) 20 // prompt for and read course name 21 System.out.println( "Please enter the course name:" ); 22 String theName = input.nextLine(); // read a line of text 23 myGradeBook.setCourseName( theName ); // set the course name 24 System.out.println(); // outputs a blank line 25 26 // display welcome message after specifying course name 27 myGradeBook.displayMessage(); 28 } // end main 29 30 } // end class GradeBookTest Initial course name is: null Please enter the course name: CS101 Introduction to Java Programming Welcome to the grade book for CS101 Introduction to Java Programming! Call set method for courseName Call displayMessage
  • 33. Visibility Modifiers and Accessor Methods By default, the class, variable, or data can be accessed by any class in the same package.  public The class, data, or method is visible to any class in any package.  private The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties.
  • 34. Passing Objects to Methods, cont. main method ReferencemyCircle 5n 5 times printAreas method Reference c myCircle: Circle radius = 1 Pass by value (here the value is 5) Pass by value (here the value is the reference for the object)
  • 35. Instance Variables, and Methods Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.
  • 36. Class Variables, Constants, and Methods Class variables are shared by all the instances of the class. Class methods are not tied to a specific object. Class constants are final variables shared by all the instances of the class.
  • 37. Class Variables, Constants, and Methods, cont. To declare class variables, constants, and methods, use the static modifier.
  • 38. Class Variables, Constants, and Methods, cont. CircleWithStaticVariable -radius -numOfObjects +getRadius(): double +setRadius(radius: double): void +getNumOfObjects(): int +findArea(): double 1 radiuscircle1:Circle -radius = 1 -numOfObjects = 2 instantiate instantiate Memory 2 5 radius numOfObjects radius is an instance variable, and numOfObjects is a class variable UML Notation: +: public variables or methods -: private variables or methods underline: static variables or metods circle2:Circle -radius = 5 -numOfObjects = 2
  • 39. Scope of Variables • The scope of instance and class variables is the entire class. They can be declared anywhere inside a class. • The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.
  • 40. The Keyword this • Use this to refer to the current object. • Use this to invoke other constructors of the object.
  • 41. Array of Objects Circle[] circleArray = new Circle[10]; An array of objects is actually an array of reference variables. So invoking circleArray[1].findArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object.
  • 42. Array of Objects, cont. reference Circle object 0circleArray[0] … circleArray circleArray[1] circleArray[9] Circle object 9 Circle object 1 Circle[] circleArray = new Circle[10];
  • 43. Class Abstraction • Class abstraction means to separate class implementation from the use of the class. • The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user.
  • 44. Java API and Core Java classes • java.lang Contains core Java classes, such as numeric classes, strings, and objects. This package is implicitly imported to every Java program. • java.awt Contains classes for graphics. • java.applet Contains classes for supporting applets.
  • 45. • java.io Contains classes for input and output streams and files. • java.util Contains many utilities, such as date. • java.net Contains classes for supporting network communications. Java API and Core Java classes, cont.
  • 46. • java.awt.image Contains classes for managing bitmap images. • java.awt.peer Platform-specific GUI implementation. • Others: java.sql java.rmi Java API and Core Java classes, cont.