Object-Oriented Programming
1
Chapter Two
Classes and Objects
2
Problem Solving
• The purpose of writing a program is to solve a problem
• Solving a problem consists of multiple activities:
• Understand the problem
• Design a solution
• Consider alternatives and refine the solution
• Implement the solution
• Test the solution
• These activities are not purely linear – they overlap and interact 3
Problem Solving…
• The key to designing a solution is breaking it down into
manageable pieces
• When we develop a software, we design separate pieces
that are responsible for certain parts of the solution
• An object-oriented approach lends itself to this kind of
solution decomposition
• We will dissect our solutions into pieces called objects and
classes.
4
Object-Oriented Programming
• Java is an object-oriented programming language
• As the term implies, an object is a fundamental entity in a Java
program
• Objects can be used effectively to represent real-world entities
• For instance, an object might represent a particular employee in
a company
• Each employee object handles the processing and data
5
management related to that employee
What is a Class?
• The two most important concepts in object-oriented programming are the class
and the object.
• A class is a kind of mold or template that dictates what objects can and cannot
do. OR
• A class is a blueprint, or prototype, that defines the variables and the methods
common to all objects of a certain kind.
6
What is an Object?
• An object is a thing, both tangible and intangible, that we can imagine.
• An object represents an entity in the real world that can be distinctly
identified.
• For example, a student, a desk, a circle, a button, and even a loan can all be
viewed as objects.
• An object has a unique identity, state, and behavior.
7
What is an Object?
• The state of an object (also known as its properties or attributes) is represented by data fields
with their current values.
• A circle object, for example, has a data field radius, which is the property that characterizes a
circle.
• The behavior of an object (also known as its actions) is defined by methods.
• To invoke a method on an object is to ask the object to perform an action.
• For example, you may define a method named getArea() for circle objects.
8
What is an Object?
• In the real world, you often have many objects of the same kind.
• For example, if you have a bicycle, yours is just one of many bicycles in the world.
• Using object-oriented terminology, we say that your bicycle object is an instance of the
class of objects known as bicycles.
• Bicycles have some state (current gear, current cadence, two wheels) and behavior (change
gears, brake) in common.
• However, each bicycle's state is independent of and can be different from that of other
bicycles.
9
Contd…
• In object-oriented software, it's also possible to have many
objects of the same kind that share characteristics:
• Rectangles
• employee records
• video clips, and so on.
• Like the bicycle manufacturers, you can take advantage of the
fact that objects of the same kind are similar and you can
create a blueprint for those objects.
10
• A software blueprint for objects is called a class .
Defining Classes
• In Java, a program is made up of a main class and any
other classes needed to support the main class.
• A class is defined via the class keyword and the name of
the class. Simple Syntax
modifier class ClassName
{ Example
// body of the class public class Student
{
} //body of the class
}
11
Creating an object
• Using new
• To create a new object, you use the new operator with
the name of the class that should be used as a template.
• The name of the class is followed by parentheses, as in
Constructor with
these three examples: arguments
Student st = new Student();
URL address = new Constructor without
argument
12
URL(“http://www.java21days.com”);
VolcanoRobot robbie = new VolcanoRobot();
What the new keyword does?
• Several things happen when you use the new operator
• The new instance of the given class is created
• Memory is allocated for it
• The constructor defined in that class is called
13
Creating an object…
• The parentheses are important; don’t leave them off.
• The parentheses can be empty, in which case the most simple, basic object is created,
or
• the parentheses can contain arguments that determine the values of instance variables
or other initial qualities of that object.
• The number and type of arguments you can use inside the parentheses with new are
defined by the class itself using a special method called a constructor.
14
Creating an object…
• If you try to create a new instance of a class with the wrong number or type of
arguments (or if you give it no arguments and it needs some):
• You’ll receive an error when you try to compile your Java program.
15
Variables
• A variable is a place where information can be stored while a
program is running.
• The value can be changed at any point in the program
• To create a variable, you must give it a name and identify what
type of information it will store.
• You also can give a variable an initial value at the same time
you create it.
• Based on their Data Type there are two variables in java
Primitive Variables 16
Reference Variables
Variables
• Based on their scope there are three types of variables in
Java
Local variables
Instance variables
Class variables
17
Primitive vs Reference Variables
• Primitive Variables
• Are created from primitive data types
• E.g. int age;
• Reference Variables
• Are used to store the address of an object
• Created from Classes
• E.g. Scanner input;
18
Local variables
• Are used inside method definitions or even smaller blocks of
statements within a method.
• You can use them only while the method or block is being executed
by the Java interpreter.
• They cease to exist afterward.
Local variable;
Eg. local to this
public void setName(String name) method only.
{
String fname;
// rest of the body
19
{
Instance variables
• Instance variable
• An attribute of one particular object
• Also called object variables
• Have values that differ from one object to another
public class Student
{
String firstName;
String fatherName;
String gName; These are instance
variables
String id;
…
} 20
Class variables
• Class variables
• To have one value shared by all objects of that class
• Defines an attribute of an entire class
• Applies to the class itself and to all its instances, so
• only one value is stored no matter how many objects of that class have been created.
21
Class variables…
• You define class variables by including the static keyword before the variable
itself
• Syntax:
Static dataType variableName;
E.g.
static String uniqueId;
22
Methods…
• Methods define an object’s behavior—that is, anything that happens when the object is created
as well as the various tasks the object can perform during its lifetime.
• Defining Methods
• In Java, a method definition has four basic parts:
• The name of the method
• A list of parameters
• The type of object or primitive type returned by the method
• The body of the method
23
Methods…
• Here’s what a basic method definition looks like:
modifier returnType methodName(type1 arg1, type2 arg2,
type3 arg3 ...)
// body of the method
} Example:
public int add(int no1,int no2){
int sum=no1+no2;
System.out.println(“The sum” + sum);
return no1+no2;
24
}
Methods…
• The returnType is the primitive type or class of the value returned by the method.
• It can be one of the primitive types, a class name, or void if the method does not return a
value at all.
• The method’s parameter list is a set of variable declarations separated by commas and set
inside parentheses.
• These parameters become local variables in the body of the method, receiving their values
when the method is called.
25
Instance methods
• Instance method
• Any method that is invoked with respect to an instance of
a class. Also called simply a method.
Example No static keyword
here
public double getArea()
//body of the method
}
26
objectReference.instanceMethod(args)
Class methods
• Class methods
• Are also known as Static methods
• have the static modifier in their declarations
• should be invoked with the class name, without the need for
creating an instance of the class, as in
ClassName.methodName(args)
• Note: You can also refer to static methods with an object reference like
instanceName.methodName(args)
• but this is discouraged because it does not make it clear that they are
class methods.
27
• A common use for static methods is to access static fields.
Class methods…
• Example
Class variable
public class Bicycle
{
Class method
static numberOfBicycles;
public static int getNumberOfBicycles()
{
return numberOfBicycles;
}
}
28
IMPORTANT!
• Instance methods can access instance variables and instance methods directly.
• Instance methods can access class variables and class methods directly.
• Class methods can access class variables and class methods directly.
• Class methods cannot access instance variables or instance methods directly—
they must use an object reference.
• Class methods cannot use the this keyword as there is no instance for this to
refer to.
29
Constructor
• A class contains constructors that are invoked to create objects from the class
blueprint.
• Constructor declarations look like method declarations—except that they
• must use the name of the class and
• have no return type. For example, Student class may have one or more
constructor(s):
See the following:
30
Constructors
31
…
}
The this keyword
• Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being
called.
• You can refer to any member of the current object from within an
instance method or a constructor by using this.
• Using this with a Field
• The most common reason for using the this keyword is because a
field is shadowed by a method or constructor parameter.
• Observe the following example: 32
• the Point class
public class Point
{
public int x = 0;
public int y = 0;
public Point(int a, int b) //constructor
{
x = a; y = b;
}
The above one could be written like this:
public class Point
{
public int x = 0;
public int y = 0;
public Point(int x, int y) //constructor
{
this.x = x; this.y = y;
}
To refer to the Point field x and y, the constructor must use
this.x and this.y respectively. 33
Controlling Access to Members of a Class
• Access level modifiers determine whether other classes can use a particular
field or invoke a particular method.
• There are two levels of access control:
• At the top level — public, or package-private (no explicit modifier).
• At the member level — public, private, protected, or package-private (no
explicit modifier).
34
Controlling Access to Members of a Class
• public
• A class may be declared with the modifier public, in
which case that class is visible to all classes everywhere.
• Default modifier
• If a class has no modifier (the default, also known as
package-private), it is visible only within its own
package (packages are named groups of related.)
35
Controlling Access to Members of a Class
• At the member level
• you can also use the public modifier or no modifier (package-private) just
as with top-level classes, and with the same meaning.
• For members, there are two additional access modifiers: private and
protected.
36
Controlling Access to Members of a Class
• The private modifier
• specifies that the member can only be accessed in its own class.
• The protected modifier
• specifies that the member can only be accessed within its own package
(as with package-private) and, in addition, by a subclass of its class in
another package.
37
Controlling Access to Members of a Class
• Figure 2.1 illustrates how a public, default, and private data field or
method in class C1 can be accessed from a class C2 in the same
package and from a class C3 in a different package.
38
• Figure 2.1
Controlling Access to Members of a Class
• The private modifier applies only to the members of a class.
• The public modifier can apply to a class or members of a class.
• Using modifiers public and private on local variables would cause a compile
error.
• In most cases, the constructor should be public.
• However, if you want to prohibit the user from creating an instance of a class, use
a private constructor.
39
Accessing class and instance variables
• Class and instance variables are used in largely the same manner as
the local variables
• You can use them in expressions, assign values to them in statements,
and so on.
• To get to the value of an instance variable, you use dot notation
• It is a form of addressing in which an instance or class variable
name has two parts:
• a reference to an object or class on the left side of the dot and
• a variable on the right side of the dot.
40
Accessing and Setting Instance Variables
• For example, if you have an object named myCustomer, and that object has a
variable called orderTotal, you refer to that variable’s value as
myCustomer.orderTotal, as in this statement:
float total = myCustomer.orderTotal;
accessing
myCustomer.orderTotal=total;
setting
41
Accessing and Setting class Variables
• Class variables
• are variables defined and stored in the class itself.
• Their values apply to the class and all its instances.
• You define class variables by including the static keyword before
the variable itself.
• If we have the following:
class FamilyMember {
static String surname = “Mendoza”;
String name;
int age;
42
}
Accessing and Setting class Variables…
Observe the following:
FamilyMember dad = new FamilyMember();
System.out.println(“Family’s surname is: “ + dad.surname);
System.out.println(“Family’s surname is: “ +
FamilyMember.surname);
• Both are possible to refer to the variable surname. But the last one is
recommended (FamilyMember.surname).
• To refer to the variable name:
dad.name correct
FamilyMember.name wrong. 43
Calling instance Methods
• Calling a method in an object is similar to referring to its instance
variables:
• Dot notation is used.
• The object whose method you’re calling is on the left side of the
dot, and
• The name of the method and its arguments are on the right side of
the dot:
myCustomer.addToOrder(itemNumber, price, quantity);
• Note that all methods must have parentheses after them, even if the
method takes no arguments:
44
myCustomer.cancelAllOrders();
Calling Class Methods
• Dot notation is used to call a class method.
• As with class variables, you can use either an instance of the class
or the class itself on the left side of the dot.
• For the same reasons noted in the discussion on class variables,
however, using the name of the class makes your code easier to
read.
• For example, the class method Math.max() takes two arguments
and returns the larger of the two. You don’t need to create a new
instance of Math; it can be called anywhere you need it, as in the
following: 45
int higherPrice = Math.max(firstPrice, secondPrice);
Access Modifiers keywords that help set the
visibility and accessibility of a
public class, its member variables,
and methods
determine whether a field or
protected method in a class, can be
used or invoked by another
private method in another class or
sub-class. 46
Garbage Collection
• If an 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.
47