3. Objective
In this chapter you will learn:
◎ What classes, objects, methods and instance variables
are.
◎ How to declare a class and use it to create an object.
◎ How to declare methods in a class to implement the
class’s behaviors.
◎ How to declare instance variables in a class to implement
the class’s attributes.
3
4. Objective Cont.
◎ How to call an object’s method to make that method
perform its task.
◎ The differences between instance variables of a class
and local variables of a method.
◎ How to use a constructor to ensure that an object’s data
is initialized when the object is created.
4
5. Introduction
◎ Java is a true OO language and therefore the underlying structure of all Java
programs is classes.
◎ Anything we wish to represent in Java must be encapsulated in a class that
defines the “state” and “behaviour” of the basic program components known as
objects.
◎ Classes create objects and objects use methods to communicate between them.
◎ They provide a convenient method for packaging a group of logically related data
items and functions that work on them.
5
6. Classes
◎ Class − is template/blueprint that describes the
behavior/state that the object of its type support.
6
Circle
centre
radius
circumference()
area()
7. Classes
◎ A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
◎ The basic syntax for a class definition:
◎ Bare bone class – no fields, no methods
7
public class Circle {
// my circle class
}
class ClassName [extends
SuperClassName]
{
[fields declaration]
[methods declaration]
}
8. Adding Fields: Class Circle with fields
◎ Add fields
◎ The fields (data) are also called the instance
varaibles.
8
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
9. Adding Methods
◎ A class with only data fields has no life. Objects created
by such a class cannot respond to any messages.
◎ Methods are declared inside the body of the class but
immediately after the declaration of data fields.
◎ The general form of a method declaration is:
9
type MethodName (parameter-list)
{
Method-body;
}
10. Adding Methods to Class Circle
10
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Method Body
12. class C
{
public static void main(String[] args)
{
System.out.println("Sample output from class C");
}
}
12
13. Rules Applicable to Source file
◎ There can be only one public class per source code file but
it can have multiple non public classes.
◎ In case there is any public class present in the source code
file, the name of the file should be the name of the class.
◎ Files with no public class can have any name for the class.
13
14. Rules Cont.
◎ Sequence of statements in a source code file should
be package >> import >> Class declaration.
◎ No Sequence rule is applied for Comments. Comments
can be there in any part of the source code file at any
location.
◎ Import and package statements should be applied to all
the classes in the same source code file.
14
15. Objects
◎ Object is the physical as well as logical entity
○ a desk, computer, chair, person, etc
◎ An object has a (current) state and behavior.
○ A dog has state (name, color, breed, hungry) and
behavior (barking, fetching, and wagging tail).
15
16. An Object in Software
A real world object may be represented in
software.
Different variables represent the state of the
object.
Various methods/functions represent the behavior
of the object.
Object Type: Light
Variable: boolean switchState;
Function: void turnSwitch(boolean on) { …. }
17. Each object has a type/class.
An object is an instance of a class/type. We write
new classes to define new types of objects.
A particular object resembles other objects of its
type. A few variables of an object may be shared
by all objects of the same type.
An Object can be mutable (has changing state) or
immutable (its methods do not change its state).
Objects can inherit properties, both state and
behavior, from other objects.
Properties of Objects
18. Syntax:
<Class_Name> ClassObjectReference = new <Class_Name>();
Example
Circle c1, c2, c3; // They hold a special value called null
// Construct the instances via new operator
c1 = new Circle();
c2 = new Circle(2.0);
c3 = new Circle(3.0, "red");
// You can Declare and Construct in the same statement
Circle c4 = new Circle();
18
19. Class of Circle cont.
◎ c1, c2 simply refers to a Circle object, not an object
itself.
19
c2
Points to nothing (Null Reference)
c2
Points to nothing (Null Reference)
null null
20. 20
Creating objects of a class
c1 = new Circle();
c2= new Circle() ;
c2= c1;
P
c1
Q
c2
Before Assignment
P
c1
Q
c2
Before Assignment
21. Automatic garbage collection
◎ The object does not have a reference and
cannot be used in future.
◎ The object becomes a candidate for automatic
garbage collection.
◎ Java automatically collects garbage periodically and
releases the memory used to be used in the future.
21
Q
23. Dot(.) operator
◎ The variables and methods belonging to a
class are formally called member variables
and member methods.
◎ To reference a member variable or method,
you must:
○ First identify the instance you are interested in,
and then,
○ Use the dot operator (.) to reference the desired
member variable or method.
23
24. Accessing Object/Circle Data
◎ Similar to C syntax for accessing data defined in a
structure.
24
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
25. Executing Methods in Object/Circle
◎ Using Object Methods:
25
Circle aCircle = new Circle();
double area;
aCircle.r = 1.0;
area = aCircle.area();
sent ‘message’ to aCircle
26. Member Methods
◎ A method (as described in the earlier
chapter):
○ receives arguments from the caller,
○ performs the operations defined in the method
body, and
○ returns a piece of result (or void) to the caller.
26
27. Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference
="+circumf);
}
}
27 Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
28. Constructors
◎ A constructor is a special method that has the
same method name as the class name.
◎ A constructor is different from an ordinary method
in the following aspects:
○ The name of the constructor method is the same as
the class name.
○ Constructor has no return type.
○ Constructor can only be invoked via the "new"
operator. Once an instance is constructed, you cannot
call the constructor anymore.
○ Constructors are not inherited
28
29. Outline of a Class Definition
There is no public static void main() method defined in class Apple.
class Apple {
// Data Fields to record state of Apple.
// Constructor for Making a New Apple.
// Methods for Behavior of Apple.
}
30. Apple Class – Writing the code.
class Apple {
// Data Fields to record state of Apple.
String color;
// Constructor for Making a New Apple.
Apple(String c) { color = c; }
// Methods for Behavior of Apple.
String getAppleColor() { return color; }
void sliceApple() {
System.out.println(“You sliced this ” + color + “ apple.”);
}
}
31. Constructors
Class Apple has a constructor:
Apple(String c) {
color = c;
}
A constructor is a special method that has no return type.
The constructor name is EXACTLY the same as the class name: Apple
A constructor constructs a new object using the new keyword:
Apple redApple = new Apple(“red”);
A constructor must initialize the state of the Apple object. In this
case, the constructor expects a color, then initializes its own color to
the given color specified.
32. Using the Apple Class
We can use the Apple class now as follows:
We write another class (here, called Application) that includes the
main() method.
class Application {
public static void main(String[] args) {
System.out.println(“Hello World Again !”);
Apple greenApple = new Apple(“green”);
System.out.println(“I made a ” + greenApple.getAppleColor()
+ “ apple, and I am learning objects.”);
}
33. Using Apple Methods
We can write more statements (using Apple methods) in another
class (for example, the Application class)
What would these statements print out?
Apple redApple = new Apple(“red”);
System.out.println(“We made a ” + redApple.getAppleColor() + “
apple.”);
redApple.sliceApple();
redApple.color = “green”;
System.out.println(“We made a ” + redApple.getAppleColor() + “ apple.”);
LAST TWO LINES INTRODUCE ISSUE OF ACCESS INTO OBJECT.
34. redApple.color = “green”;
System.out.println(“We made a ” + redApple.getAppleColor() + “ apple?”);
We created a new red apple.
However, we can access the red apple’s color outside the class, and
somehow change it to green. This is obviously not what we want.
Want to limit access:
In the Apple class, we should have written:
private String color; // Now, can’t change color outside Apple class.
Access Into Objects
35. Private, Public, Nothing Specified.
Private: Can only access variable or method
within the class itself. (Within Apple class)
Public: Can access variable or method everywhere.
(Inside Apple class and Application class)
Nothing Specified: So far, we have not specified any
private or public access. This means
the variable or method is accessible
in the same package (for now, this
means same as public)
36. Completed Apple Class
public class Apple {
// Data Fields to record state of Apple.
private String color;
// Constructor for Making a New Apple.
public Apple(String c) { color = c; }
// Methods for Behavior of Apple.
public String getAppleColor() { return color; }
public void sliceApple() {
System.out.println(“You sliced this “ + color + “ apple.”);
}
}
37. redApple.color can’t write this statement
anymore. The access to the object’s color field
in the Application class is prohibited.
Once we create an apple with a certain color, then it can’t
change.
IF we were writing a leaf class, we might want to have its color
be changeable as the seasons change.
38. Static Keyword
1. Want all Point Objects to share same Origin.
Point aPoint = new Point();
Point bPoint = new Point();
aPoint.origin is a separate object from bPoint.origin.
SOLUTION: Use static keyword. Now, all Point objects share a
common origin:
aPoint.origin is same object as bPoint.origin.
39. How does the Static Keyword affect Attributes
◎ When you create a static attribute it “only exists in
the class”. Although each new object has that specific
variable, that variable is only a reference to the same
variable in the class. This means:
○ For all the objects created from that class the static variable
will have the same value in all the objects since they all refer
to the same place in the class
○ If the variables is changed in one of the objects/class this will
change this variable in all objects/class since it really only
exists in one place.
40. How does the Static Keyword affect Methods
◎ Like static attributes,
static methods only exist in the class.
◎ Static methods cannot refer to non-static variables in the
class.
41. Final Keyword
2. Want Origin to never change.
Point aPoint = new Point();
aPoint.origin = new Point();
aPoint.origin.x = 0.0;
aPoint.origin = new Point();// Bad – Changes origin
Want to finalize the origin.
SOLUTION: Use final keyword. Now, all Point objects have the same
origin that cannot change.
42. How does the final Keyword affect attributes and
methods?
◎ It does not let you change the value of a variable after it has
been initialized.
◎ A final variable is a constant.
◎ A final method: prevents someone from overriding the
method in a subclass (discussed in a later lecture).
43. Revised Point Class
class Point {
double x;
double y;
String label = “node point”;
boolean errorFlag = false;
// Added a totalPoints field for counting objects.
static int totalPoints = 0;
static final Point origin = new Point();
}
44. Review Example: class Point3D
class Point3D {
double x;
static double y;
static final double z = 7.0;
}
1. Identify class variables (those belonging to all 3DPoint objects)
2. Identify instance variables (those particular to each 3DPoint object)
3. What happens here to p1.x, p2.x, p1.y, p2.y, and p1.z, p2.z
after each statement?
Point3D p1 = new Point3D();
Point3D p2 = new Point3D();
p1.x = 1.0;
p1.y = 2.0;
p2.x = 3.0;
p2.y = 4.0;
Point3D.z = 8.2;
p2.z = 9.9;
45. Adding Constructors
class Point {
double x, y;
String label = “node point”;
boolean errorFlag = false;
static int totalPoints = 0;
static final Point origin = new Point(0.0, 0.0);
// Construct a new Point – Initialize All empty variables (state).
Point(double xPos, double yPos) {
x = xPos; y = yPos;
++totalPoints;
}
} // End Class Point
46. Multiple Constructors
class Point {
…
static int totalPoints = 0;
static final Point origin = new Point(0.0, 0.0, “Origin”);
// Construct a new Point given coordinates.
Point(double x, double y) {
this.x = x; this.y = y;
++totalPoints;
}
// Another overloaded constructor using this keyword.
Point(double x, double y, String label) {
this(x, y); //calls alternate constructor
this.label = label;
}
} // End Class Point
47. this Keyword
The this keyword is a reference within the class to the
object instance that is being created.
Inside the class Point, the this reference points to the specific Point object
being created.
this.x is the same as using the object’s x parameter unmistakably.
this() would call the default constructor.
this(4.4, 2.8) would call the first constructor.
this.doMethod() would call the object’s method.
48. public class Point {
// Data Fields
private double x, y;
private String label = “node point”;
private boolean errorFlag = false;
private static int totalPoints = 0;
public static final Point origin =
new Point(0.0, 0.0, “Origin”);
//Constructors
private Point(double x, double y) {}
public Point(double x, double y, String
label) {}
// New Methods
public double getX() {}
public double getY() {}
public String getLabel() {}
public static intgetNumberOfPoints(){}
public double distanceTo(PointpointTwo) {}
} // End Class Point
POINT
+getX()
+getY()
+getNumberOfPoints()
+distanceTo(Point two)
+equals(Object two)
+toString()
x
y
label
totalPoints
errorFlag
origin
49. Exercise
◎ Define a class book
◎ create objects for the class book
◎ add data fields and methods to
classes
◎ access data fields and methods
to classes
49