Chapter 6 Objects and Classes
Working of java
OO Programming Concepts
Creating Objects and Object Reference Variables
Differences between primitive data type and object type
Automatic garbage collection
Constructors
Modifiers (
public
,
private
and
static
)
Instance and Class Variables and Methods
OO Programming Concepts
data field 1
method n data field n
method 1 An object
...
...
State
Behavior
Data Field radius = 5
JAVA Classes
• The class is the fundamental concept in JAVA (and other
OOPLs)
• A class describes some data object(s), and the operations
(or methods) that can be applied to those objects
• Every object and method in Java belongs to a class
• Classes have data (fields) and code (methods) and classes
(member classes or inner classes)
• Static methods and fields belong to the class itself • Others belong to instances
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
Class Declaration
class Circle {
double radius = 1.0;
double findArea(){
return radius * radius * 3.14159;
}
Declaring Object Reference Variables
ClassName objectReference;
Example:
Creating Objects
objectReference = new ClassName();
Example:
myCircle = new Circle();
Declaring/Creating Objects
in a Single Step
ClassName
objectReference
= new
ClassName();
Example:
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 2 j 2 After: i 2 j
Object type assignment c1 = c2
Before: c1 c2 After: c1 c2 c2: Circle
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
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
Accessing Objects
•
Referencing the object’s data:
objectReference.data
myCircle.radius
•
Invoking the object’s method:
objectReference.method
Constructors
• Classes should define one or more methods to create or construct instances of the class
• Their name is the same as the class name
– note deviation from convention that methods begin with lower case
• Constructors are differentiated by the number and types of
their arguments
– An example of overloading
• If you don’t define a constructor, a default one will be
created.
• Constructors automatically invoke the zero argument
constructor of their superclass when they begin (note that this yields a recursive process!)
Constructors
Circle(double r) {
radius = r;
}
Circle() {
radius = 1.0;
}
myCircle = new Circle(5.0);
Constructors are a
special kind of
methods that are
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
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.
Passing Objects to Methods
•
Passing by value (the value is the reference
to the object)
Passing Objects to Methods, cont.
main method Reference myCircle 5n 5
times printAreas method Reference c myCircle: Circle radius = 1
Pass by value (here the value is 5)
Instance
Variables, and Methods
Instance variables belong to a specific instance.
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.
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
The static keyword
•
Java methods and variables can be declared static
•
These exist
independent of any object
•
This means that a Class’s
–static methods can be called even if no objects of that
class have been created and
–static data is “shared” by all instances (i.e., one rvalue
per class instead of one per instance
24
class StaticTest {static int i = 47;} StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); // st1.i == st2.I == 47
Methods
• A method is a named sequence of code that can be invoked
by other Java code.
• A method takes some parameters, performs some
computations and then optionally returns a value (or object).
• Methods can be used as part of an expression statement.
public float convertCelsius(float tempC) {
Method Signatures
• A method signature specifies:
– The name of the method.
– The type and name of each parameter.
– The type of the value (or object) returned by the method. – The checked exceptions thrown by the method.
– Various method modifiers.
– modifiers type name ( parameter list ) [throws exceptions ]
public float convertCelsius (float tCelsius ) {}
Methods, arguments and return values
• Java methods are like C/C++ functions. General case:
returnType methodName ( arg1, arg2, … argN) { methodBody
}
The return keyword exits a method optionally with a value
int storage(String s) {return s.length() * 2;} boolean flag() { return true; }
float naturalLogBase() { return 2.718f; } void nothing() { return; }
void nothing2() {}
Simple Class and Method
Class
Fruit
{
int
grams
;
int
cals_per_gram
;
int
total_calories
() {
return(
grams
*
cals_per_gram
);
}
Command Line Arguments
C:\UMBC\331\java>type echo.java
// This is the Echo example from the Sun tutorial
class echo {
public static void main(String args[]) { for (int i=0; i < args.length; i++) { System.out.println( args[i] );
} }}
C:\UMBC\331\java>javac echo.java
C:\UMBC\331\java>java echo this is pretty silly this
is
Arrays
• Am array is a list of similar things • An array has a fixed:
–
name
–
type
–
length
• These must be declared when the array is created.
• Arrays sizes cannot be changed during the execution of the
myArray has room for 8 elements
the elements are accessed by their index
in Java, array indices start at 0
3
6
3
1
6
3
4
1
myArray =
Declaring Arrays
int myArray[];
declares
myArray
to be an array of integers
myArray =
new
int[8];
sets up 8 integer-sized spaces in memory, labelled
myArray[0]
to
myArray[7]
int
myArray[] =
new
int[8];
Declaring the Array
1. Declare the array
private Student studentList[];
–
this declares studentList
2 .Create the array
studentList =
new
Student[10];
–
this sets up 10 spaces in memory that can
hold references to Student objects
3. Create Student objects and add them to the array:
Assigning Values
• refer to the array elements by index to store values in them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3;
...
• can create and initialise in one step:
Iterating Through Arrays
•
for
loops are useful when dealing with arrays:
for (int i = 0; i < myArray.length;
i++) {
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]
Array of Objects, cont.
Circle[] circleArray = new
Circle[10];
reference circleArray[0] Circle object 0
…
circleArray
circleArray[1]
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
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
•
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.awt.image
Contains classes for managing bitmap images.
•
java.awt.peer
Platform-specific GUI implementation.
•
Others:
java.sql
java.rmi
Java Development Kit
•
javac
- The Java Compiler
•
java
- The Java Interpreter
•
jdb
- The Java Debugger
•
appletviewer
-Tool to run the applets
•
javap - to print the Java bytecodes
•
javaprof - Java profiler
•
javadoc - documentation generator