SlideShare une entreprise Scribd logo
1  sur  46
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.

Contenu connexe

Tendances

Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaEdureka!
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingSyed Faizan Hassan
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Object and class in java
Object and class in javaObject and class in java
Object and class in javaUmamaheshwariv1
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++NainaKhan28
 

Tendances (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
C++ classes
C++ classesC++ classes
C++ classes
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Object and class in java
Object and class in javaObject and class in java
Object and class in java
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 

Similaire à Java chapter 4

UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptxakila m
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part IIIntro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part IIBlue Elephant Consulting
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptxHailsh
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Asfand Hassan
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#ANURAG SINGH
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)Umar Farooq
 
New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15myrajendra
 
Java lec class, objects and constructors
Java lec class, objects and constructorsJava lec class, objects and constructors
Java lec class, objects and constructorsJan Niño Acierto
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 

Similaire à Java chapter 4 (20)

UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
Module 3 Class and Object.ppt
Module 3 Class and Object.pptModule 3 Class and Object.ppt
Module 3 Class and Object.ppt
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part IIIntro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptx
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
 
9 cm604.14
9 cm604.149 cm604.14
9 cm604.14
 
New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15
 
Java lec class, objects and constructors
Java lec class, objects and constructorsJava lec class, objects and constructors
Java lec class, objects and constructors
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
06slide
06slide06slide
06slide
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Ppt chapter05
Ppt chapter05Ppt chapter05
Ppt chapter05
 

Plus de Abdii Rashid

object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examplesAbdii Rashid
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examplesAbdii Rashid
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printAbdii Rashid
 
Chapter 1 introduction haramaya
Chapter 1 introduction haramayaChapter 1 introduction haramaya
Chapter 1 introduction haramayaAbdii Rashid
 

Plus de Abdii Rashid (9)

Java chapter 7
Java chapter 7Java chapter 7
Java chapter 7
 
Java chapter 6
Java chapter 6Java chapter 6
Java chapter 6
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Java chapter 2
Java chapter 2Java chapter 2
Java chapter 2
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for print
 
Chapter 7 graphs
Chapter 7 graphsChapter 7 graphs
Chapter 7 graphs
 
Chapter 1 introduction haramaya
Chapter 1 introduction haramayaChapter 1 introduction haramaya
Chapter 1 introduction haramaya
 

Dernier

Al Jaddaf Housewife Call Girls +971509530047 Al Jaddaf Call Girls
Al Jaddaf Housewife Call Girls +971509530047 Al Jaddaf Call GirlsAl Jaddaf Housewife Call Girls +971509530047 Al Jaddaf Call Girls
Al Jaddaf Housewife Call Girls +971509530047 Al Jaddaf Call Girlstiril72860
 
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full NightCall Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Nightssuser7cb4ff
 
Dwarka Call Girls 9643097474 Phone Number 24x7 Best Services
Dwarka Call Girls 9643097474 Phone Number 24x7 Best ServicesDwarka Call Girls 9643097474 Phone Number 24x7 Best Services
Dwarka Call Girls 9643097474 Phone Number 24x7 Best Servicesnajka9823
 
Available to Promise Oracle R12 ATP.pptx
Available to Promise Oracle R12 ATP.pptxAvailable to Promise Oracle R12 ATP.pptx
Available to Promise Oracle R12 ATP.pptxbskumar_slideshare
 
BIODIVERSITY QUIZ ELIMINATION ROUND.pptx
BIODIVERSITY QUIZ ELIMINATION ROUND.pptxBIODIVERSITY QUIZ ELIMINATION ROUND.pptx
BIODIVERSITY QUIZ ELIMINATION ROUND.pptxROLANARIBATO3
 
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170simranguptaxx69
 
World Environment Day PPT slides for Earth DAy arpil 2022
World Environment Day PPT slides for Earth DAy arpil 2022World Environment Day PPT slides for Earth DAy arpil 2022
World Environment Day PPT slides for Earth DAy arpil 2022herebasit
 
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一F dds
 
Group 4The Species of the Atlantic Forest.pdf
Group 4The Species of the Atlantic Forest.pdfGroup 4The Species of the Atlantic Forest.pdf
Group 4The Species of the Atlantic Forest.pdfs2015004
 
885MTAMount DMU University Bachelor's Diploma in Education
885MTAMount DMU University Bachelor's Diploma in Education885MTAMount DMU University Bachelor's Diploma in Education
885MTAMount DMU University Bachelor's Diploma in Educationz xss
 
办理(Victoria毕业证书)维多利亚大学毕业证成绩单原版一比一
办理(Victoria毕业证书)维多利亚大学毕业证成绩单原版一比一办理(Victoria毕业证书)维多利亚大学毕业证成绩单原版一比一
办理(Victoria毕业证书)维多利亚大学毕业证成绩单原版一比一z xss
 
global trend Chapter 1.presentation power point
global trend Chapter 1.presentation power pointglobal trend Chapter 1.presentation power point
global trend Chapter 1.presentation power pointyohannisyohannis54
 
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...Delhi Escorts
 
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhidelih Escorts
 
Call In girls Connaught Place (DELHI)⇛9711147426🔝Delhi NCR
Call In girls Connaught Place (DELHI)⇛9711147426🔝Delhi NCRCall In girls Connaught Place (DELHI)⇛9711147426🔝Delhi NCR
Call In girls Connaught Place (DELHI)⇛9711147426🔝Delhi NCRjennyeacort
 
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...Aqsa Yasmin
 

Dernier (20)

Al Jaddaf Housewife Call Girls +971509530047 Al Jaddaf Call Girls
Al Jaddaf Housewife Call Girls +971509530047 Al Jaddaf Call GirlsAl Jaddaf Housewife Call Girls +971509530047 Al Jaddaf Call Girls
Al Jaddaf Housewife Call Girls +971509530047 Al Jaddaf Call Girls
 
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full NightCall Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
 
PLANTILLAS DE MEMORAMA CIENCIAS NATURALES
PLANTILLAS DE MEMORAMA CIENCIAS NATURALESPLANTILLAS DE MEMORAMA CIENCIAS NATURALES
PLANTILLAS DE MEMORAMA CIENCIAS NATURALES
 
Dwarka Call Girls 9643097474 Phone Number 24x7 Best Services
Dwarka Call Girls 9643097474 Phone Number 24x7 Best ServicesDwarka Call Girls 9643097474 Phone Number 24x7 Best Services
Dwarka Call Girls 9643097474 Phone Number 24x7 Best Services
 
Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...
Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...
Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...
 
Available to Promise Oracle R12 ATP.pptx
Available to Promise Oracle R12 ATP.pptxAvailable to Promise Oracle R12 ATP.pptx
Available to Promise Oracle R12 ATP.pptx
 
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
 
BIODIVERSITY QUIZ ELIMINATION ROUND.pptx
BIODIVERSITY QUIZ ELIMINATION ROUND.pptxBIODIVERSITY QUIZ ELIMINATION ROUND.pptx
BIODIVERSITY QUIZ ELIMINATION ROUND.pptx
 
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
 
World Environment Day PPT slides for Earth DAy arpil 2022
World Environment Day PPT slides for Earth DAy arpil 2022World Environment Day PPT slides for Earth DAy arpil 2022
World Environment Day PPT slides for Earth DAy arpil 2022
 
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
 
Group 4The Species of the Atlantic Forest.pdf
Group 4The Species of the Atlantic Forest.pdfGroup 4The Species of the Atlantic Forest.pdf
Group 4The Species of the Atlantic Forest.pdf
 
885MTAMount DMU University Bachelor's Diploma in Education
885MTAMount DMU University Bachelor's Diploma in Education885MTAMount DMU University Bachelor's Diploma in Education
885MTAMount DMU University Bachelor's Diploma in Education
 
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
 
办理(Victoria毕业证书)维多利亚大学毕业证成绩单原版一比一
办理(Victoria毕业证书)维多利亚大学毕业证成绩单原版一比一办理(Victoria毕业证书)维多利亚大学毕业证成绩单原版一比一
办理(Victoria毕业证书)维多利亚大学毕业证成绩单原版一比一
 
global trend Chapter 1.presentation power point
global trend Chapter 1.presentation power pointglobal trend Chapter 1.presentation power point
global trend Chapter 1.presentation power point
 
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
 
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
 
Call In girls Connaught Place (DELHI)⇛9711147426🔝Delhi NCR
Call In girls Connaught Place (DELHI)⇛9711147426🔝Delhi NCRCall In girls Connaught Place (DELHI)⇛9711147426🔝Delhi NCR
Call In girls Connaught Place (DELHI)⇛9711147426🔝Delhi NCR
 
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
 

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.