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
PDF
ITFT-Classes and object in java
PDF
Lect 1-java object-classes
PPT
Lect 1-class and object
PPT
Object and class
PPTX
Class or Object
PPTX
Java class,object,method introduction
PDF
Classes and objects in java
Java chapter 5
ITFT-Classes and object in java
Lect 1-java object-classes
Lect 1-class and object
Object and class
Class or Object
Java class,object,method introduction
Classes and objects in java

What's hot (20)

PPTX
Classes and objects
PPT
4 Classes & Objects
PDF
Java OOP Programming language (Part 3) - Class and Object
PDF
Core java complete notes - Contact at +91-814-614-5674
PPTX
Classes and objects
PPS
Introduction to class in java
PPTX
C++ classes
PPTX
Classes, objects in JAVA
PPT
Class and object in C++
PDF
Python Class | Python Programming | Python Tutorial | Edureka
PPTX
C++ And Object in lecture3
PDF
Class and object in C++ By Pawan Thakur
PPTX
Class introduction in java
PDF
Java Methods
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PDF
How to write you first class in c++ object oriented programming
PDF
Class and Objects in Java
PPT
Object and Classes in Java
PPT
Object and class in java
PPT
Class and object in c++
Classes and objects
4 Classes & Objects
Java OOP Programming language (Part 3) - Class and Object
Core java complete notes - Contact at +91-814-614-5674
Classes and objects
Introduction to class in java
C++ classes
Classes, objects in JAVA
Class and object in C++
Python Class | Python Programming | Python Tutorial | Edureka
C++ And Object in lecture3
Class and object in C++ By Pawan Thakur
Class introduction in java
Java Methods
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
How to write you first class in c++ object oriented programming
Class and Objects in Java
Object and Classes in Java
Object and class in java
Class and object in c++
Ad

Similar to Java chapter 4 (20)

PPT
Core Java unit no. 1 object and class ppt
PPT
Core Java unit no. 1 object and class ppt
PPTX
UNIT - IIInew.pptx
PDF
Chapter- 2 Introduction to Class and Object.pdf
PPT
Module 3 Class and Object.ppt
PPTX
Lecture 5
PPT
packages and interfaces
PPTX
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
PPTX
Java Reflection Concept and Working
PDF
Java Programming - 04 object oriented in java
PPTX
Class and Object.pptx
PPTX
C# classes objects
PPT
Sonu wiziq
PPT
Oop lec 4(oop design, style, characteristics)
PPT
Oops concept in c#
PDF
C# (This keyword, Properties, Inheritance, Base Keyword)
PPT
9 cm604.14
PPTX
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
PPT
New operator and methods.15
PPT
Java lec class, objects and constructors
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
UNIT - IIInew.pptx
Chapter- 2 Introduction to Class and Object.pdf
Module 3 Class and Object.ppt
Lecture 5
packages and interfaces
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Java Reflection Concept and Working
Java Programming - 04 object oriented in java
Class and Object.pptx
C# classes objects
Sonu wiziq
Oop lec 4(oop design, style, characteristics)
Oops concept in c#
C# (This keyword, Properties, Inheritance, Base Keyword)
9 cm604.14
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
New operator and methods.15
Java lec class, objects and constructors
Ad

More from Abdii Rashid (9)

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

Recently uploaded (20)

DOCX
Epoxy Coated Steel Bolted Tanks for Agricultural Waste Biogas Digesters Turns...
PPTX
Biodiversity.udfnfndrijfreniufrnsiufnriufrenfuiernfuire
PPTX
"One Earth Celebrating World Environment Day"
PDF
Bai bao Minh chứng sk2-DBTrong-003757.pdf
PDF
Cave Diggers Simplified cave survey methods and mapping
PDF
Tree Biomechanics, a concise presentation
PDF
Blue Economy Development Framework for Indonesias Economic Transformation.pdf
PDF
Effect of salinity on biochimical and anatomical characteristics of sweet pep...
PPTX
Environmental Ethics: issues and possible solutions
PPTX
Plant_Cell_Presentation.pptx.com learning purpose
PPTX
Green and Cream Aesthetic Group Project Presentation.pptx
PPT
Environmental pollution for educational study
PDF
Global Natural Disasters in H1 2025 by Beinsure
PPTX
ser tico.pptxXYDTRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRY
PDF
FMM Slides For OSH Management Requirement
PPTX
NSTP1 NSTP1NSTP1NSTP1NSTP1NSTP1NSTP1NSTP
PPTX
Disposal Of Wastes.pptx according to community medicine
PDF
Effective factors on adoption of intercropping and it’s role on development o...
PDF
The Role of Non-Legal Advocates in Fighting Social Injustice.pdf
PPTX
Office Hours on Drivers of Tree Cover Loss
Epoxy Coated Steel Bolted Tanks for Agricultural Waste Biogas Digesters Turns...
Biodiversity.udfnfndrijfreniufrnsiufnriufrenfuiernfuire
"One Earth Celebrating World Environment Day"
Bai bao Minh chứng sk2-DBTrong-003757.pdf
Cave Diggers Simplified cave survey methods and mapping
Tree Biomechanics, a concise presentation
Blue Economy Development Framework for Indonesias Economic Transformation.pdf
Effect of salinity on biochimical and anatomical characteristics of sweet pep...
Environmental Ethics: issues and possible solutions
Plant_Cell_Presentation.pptx.com learning purpose
Green and Cream Aesthetic Group Project Presentation.pptx
Environmental pollution for educational study
Global Natural Disasters in H1 2025 by Beinsure
ser tico.pptxXYDTRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRY
FMM Slides For OSH Management Requirement
NSTP1 NSTP1NSTP1NSTP1NSTP1NSTP1NSTP1NSTP
Disposal Of Wastes.pptx according to community medicine
Effective factors on adoption of intercropping and it’s role on development o...
The Role of Non-Legal Advocates in Fighting Social Injustice.pdf
Office Hours on Drivers of Tree Cover Loss

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.