Professional Documents
Culture Documents
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021
Chapter 4
Classes and Objects
With the knowledge you now have of the basics of the Java programming language, you can learn to write your own
classes. In this chapter, you will find information about defining your own classes, including declaring member variables,
methods, and constructors. You will learn to use your classes to create objects, and how to use the objects you create.
4.1. Introduction
Object-oriented programming is modeled on how, in the real world, objects are often made up of many kinds
of smaller objects. This capability of combining objects, however, is only one very general aspect of object-
oriented programming. Object-oriented programming provides several other concepts and features to make
creating and using objects easier and more flexible, and the most important of these features is that of classes.
A class is a template for multiple objects with similar features. Classes embody all the features of a
particular set of objects. When you write a program in an object-oriented language, you don’t define
actual objects. You define classes of objects.
Object: An instance of a class is another word for an actual object. If classes are an abstract
representation of an object, an instance is its concrete representation.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color,
breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current
pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes).
Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-
oriented programming.
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior.
An object stores its state in fields (variables in some programming languages) and exposes its behavior through
methods (functions in some programming languages). Methods operate on an object's internal state and serve
as the primary mechanism for object-to-object communication. Hiding internal state and requiring all
interaction to be performed through an object's methods is known as data encapsulation — a fundamental
principle of object-oriented programming.
4.2. Classes
4.2.1. Class Declaration/Defining Classes
A class declaration defines a new named reference type and describe how it is implemented. A top level class
is a class that is not a nested class. A nested class is any class whose declaration occurs within the body of
another class or interface.
A minimal class declaration which contains only the required components can be defined as:
class ClassName {
// Fields/Variables
// Constructors
// Methods
}
- Methods
- Nested classes, and
- Nested interfaces
Constructors
Instance initializers
Static initializers
The members of a class include both declared and inherited members. Declared Members of a class are the
type's fields, methods, and nested types (nested classes and interfaces). They are declared in the body of the
class.
Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
- Local variables are visible only within the declared method, constructor, or block. They are not
accessible from the rest of the class.
- There is no default value for local variables, so local variables should be declared and an initial
value should be assigned before the first use.
Parameters: name argument values passed to a method or a constructor. For example; in the main
method, the args variable is the parameter to this method. Parameters are always classified as
"variables" not "fields". This applies to other parameter such as lambda expression and exception
handlers.
}
}
Field Modifier: are keywords that you add to those definitions to change their meanings. Zero or more
modifiers
Access Control Modifiers: used to set access levels, i.e. what other classes have access to a
member field. The four access levels are:
The default: Zero/ No modifiers are needed. Visible to the package,
Public: Visible to the world; the field is accessible from all classes.
Private: Visible to the class only; the field is accessible only within its own class
Protected: Visible to the package and all subclasses
Non-Access Modifiers: Java provides a number of non-access modifiers to achieve many
other functionality. Such as, static, final, transient, volatile.
Data Type: All variables must have a type. You can use primitive types such as int, float, boolean, etc.
Or you can use reference types, such as strings, arrays, or objects.
Field Name: All variables, whether they are fields, local variables, or parameters, follow the same
naming rules and conventions that were covered in the
4.4. Methods
A Java method is a collection of statements that are grouped together to perform an operation. The method
is for creating reusable code. Methods enable code sharing and reuse. In earlier chapters you have used
predefined methods such as System.out.println. When you call the System.out.println() method, for example,
the system actually executes several statements in order to display a message on the console.
All the statements in Java must reside within methods. Methods are similar to functions except they
belong to classes. A method has a return value, a name and usually some parameters initialized
when it is called with some arguments.
A method declares executable code that can be invoked, passing a fixed number of values as
arguments.
4.4.1. Defining a Method
A method definition consists of a method header and a method body. The syntax for defining a method is as
follows:
Modifier − It defines the access type of the method and it is optional to use. Such as public, private,
and others you will learn about later.
Return Value Type: is the data type of the value the method returns.
- It can be:
Primitive types: such as int, float, boolean, etc.;
Reference types: such as strings, arrays, or objects, or
The keyword void.
- Some methods perform desired operations without returning a value.
In this case, the return Value Type is the keyword void.
This kind of method is known as void method.
Example: the main method, System.out.println, etc.
- A method may return a value. If a method returns a value, it is called a value returning
method. A return statement is required for a value-returning method.
Method Name: is any legal identifier.
- By convention, method names should be a verb in lowercase. If a name consists of several
words, concatenate them into one, making the first word lowercase and capitalizing the first
letter of each subsequent word.
For example: run, runFast, getFinalData, etc.
- A method has a unique name within its class. However, a method might have the same name
as other methods due to method overloading.
Parameter List: refers to the type, order, and number of the parameters of a method.
- It is a comma-delimited list of input parameters, enclosed by parentheses, ().
- They are optional; that is, a method may contain no parameters. If there are no parameters,
you must use empty parentheses.
- You need to declare a separate data type for each parameter. For instance, max(int num1, int
num2) is correct, but max(int num1, num2) is wrong.
- The variables declared in the method definition are known as formal parameters or simply
parameters. They like a placeholder.
- When a method is invoked, you pass a value to the parameter. This value is referred to as an
actual parameter or argument.
Method Body: contains a collection of statements that define what the method does.
- It is the method's code enclosed between braces, {}.
- The variables declared in the method body are known as local variables.
- For a value-returning method, a return statement using the keyword return is required. The
method terminates when a return statement is executed.
Example:
Let’s look at a method created to find which of two integers is bigger. This method, named max, has two int
parameters, num1 and num2, the larger of which is returned by the method. The following Figure illustrates
the components of this method.
Here:
methodName(actual parameters)
There are two ways to call a method, depending on whether the method returns a value or not.
o If the method returns a value, a call to the method is usually treated as a value. For example:
int larger = max(3, 4);
System.out.println(max(3, 4));
o If the method returns void, a call to the method must be a statement. For example, the
method println returns void. The following call is a statement:
System.out.println("Welcome to Java!");
When a program calls a method, program control is transferred to the called method. A called method
returns control to the caller when its return statement is executed or when its method ending closing
brace is reached.
o A return statement is required for a value-returning method.
o A return statement is not needed for a void method, but it can be used for terminating the
method and returning to the method’s caller. The syntax is simply return;
Example:
Following is the example to demonstrate how to define a method and how to call it.
This program contains the main method and the max method. The main method is just like any other
method except that it is invoked by the JVM.
In this example, the main method invokes max(i, j) , which is defined in the same class with the main
method.
When the max method is invoked, variable i’s value 5 is passed to num1, and variable j’s value 2 is
passed to num2 in the max method. The flow of control transfers to the max method. The max method
is executed. When the return statement in the max method is executed, the max method returns the
control to its caller (in this case the caller is the main method). This process is illustrated in the Figure
bellow.
This method is a void method, which does not return any value.
Call to a void method must be a statement i.e. printGrade(93.5);.
- It is a Java statement which ends with a semicolon as shown in the following example.
public class ExampleVoid{
public static void main(String[] args){
printGrade(93.3);
}
You cannot overload methods based on different modifiers or return types, i.e., you cannot
declare two methods with the same signature even if they have a different return type.
You cannot declare more than one method with the same name and the same number and
type of arguments, because the compiler cannot tell them apart.
Overloaded methods are differentiated by the number and the type of the arguments passed
into the method. The Java compiler determines which method is used based on the method
signature.
- For Example: max(1, 2.5), max(1.2, 2.3, 4.3) and max(1.2, 3,5) are distinct and unique
methods because they require different argument types.
4.5. Constructors
A class contains constructors that are invoked to create objects from the class blueprint. Constructor
declarations look like method declarations—except that they use the name of the class and have no return
type.
When a class is declared without any explicitly defined constructor, a default constructor is provided
automatically.
o It is a no-argument constructor with an empty body.
o However, once you define your own constructor, the default constructor is no longer used.
Syntax: Following is the syntax of a constructor
new ClassName(arguments);
For example, the following class has two constructors: one no argument constructor and a parameterized
constructor; as follow:
// no arg constructor
public ClassName() {
num1=12;
num2=34;
}
// a parameterized constructor
public ClassName(int x, int y) {
num1=x;
num2=y;
}
. . .
}
When you write a Java program, you define a set of classes. Classes are templates for objects; for the most
part, you merely use the class to create instances and then work with those instances.
DBU, Department of Electrical and Computer Engineering, 3th Year 11
ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021
ClassName refVarName;
Where:
- ClassName is the name of the class you want to create an instance of. A class is essentially a
programmer-defined type. A class is a reference type, which means that a variable of the class type
can reference an instance of the class.
- reVarName: is any valid Java identifier.
- For example: The following statement declares the variable myCircle to be of the Circle type:
Circle myCircle;
Simply declaring a reference variable does not create an object. It is just a variable declarations that associate
a variable name with an object type. A variable in this state, which currently references no object. You must
assign an object to myCircle before you use it in your code. Otherwise, you will get a compiler error. For that,
you need to use the new operator, as described in the next section.
Step 2: Instantiation a Class
The 'new' keyword is a Java operator that creates the object. It instantiates a class by allocating
memory for a new object and returning a reference to that memory. The new operator also invokes
the object constructor.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you
create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
The new operator requires a single, postfix argument: a call to a constructor. The name of the
constructor provides the name of the class to instantiate.
The new operator returns a reference to the object it created. This reference is usually assigned to a
variable of the appropriate type, like:
Circle myCircle;
myCircle=new Circle();
The reference returned by the new operator does not have to be assigned to a variable. It can also
be used directly in an expression. For example:
int x= new Circle().radius;
All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler
automatically provides a no-argument constructor, called the default constructor. This default
constructor calls the class parent's no-argument constructor, or the Object constructor if the class
has no other parent. If the parent has no constructor (Object does have one), the compiler will reject
the program.
Using the syntax shown below, you can write a single statement that combines the declaration of an
object reference variable, the creation of an object, and the assigning of an object reference to the
variable.
ClassName refVarName=new ClassName(arguments);
Instance variables can be accessed directly by calling the variable name inside the class. To refer an object's
fields, you can use the following syntax:
refVarName.fieldName;
Static variables can be accessed by calling with the class name, as follow:
ClassName.fieldName;
refVarName.methodName(arguments); // or
refVarName.methodName();
Example:
public class ClassOne{
int num1=32;
int num2=12;
X=44
Note
A class can have references to objects of other classes as members. This is called composition and is
sometimes referred to as a has-a relationship.
DBU, Department of Electrical and Computer Engineering, 3th Year 14
ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
But it could have been written like this:
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy
of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member
variables. The constructors provide a default value for any member variable whose initial value is not provided
by an argument. For example, the no-argument constructor creates a 1x1 Rectangle at coordinates 0,0. The
two-argument constructor calls the four-argument constructor, passing in the width and height but always
using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number
and the type of arguments.
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. 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.
The following table shows the access to members permitted by each modifier.
Access Levels
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
The first data column indicates whether the class itself has access to the member defined by the access level.
As you can see, a class always has access to its own members. The second column indicates whether classes
in the same package as the class (regardless of their parentage) have access to the member. The third column
indicates whether subclasses of the class declared outside this package have access to the member. The fourth
column indicates whether all classes have access to the member.
such cases. A static variable represents class wide information—all objects of the class share the same piece
of data. The declaration of a static variable begins with the keyword static.
Use a static variable when all objects of a class must use the same copy of the variable.
Static variables have class scope. We can access a class’s public static members through a reference to any
object of the class, or by qualifying the member name with the class name and a dot (.), as in Math.random()
. A class’s private static class members can be accessed by client code only through methods of the class.
Actually, static class members exist even when no objects of the class exist—they’re available as soon as the
class is loaded into memory at execution time. To access a public static member when no objects of the class
exist (and even when they do), prefix the class name and a dot (.) to the static member, as in Math.PI. To
access a private static member when no objects of the class exist, provide a public static method and call it by
qualifying its name with the class name and a dot.
A static method cannot access non-static class members, because a static method can be called even when no
objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static
method. The this reference must refer to a specific object of the class, and when a static method is called,
there might not be any objects of its class in memory.
Let’s see how this principle applies to instance variables. Some of them need to be modifiable and some do
not. You can use the keyword final to specify that a variable is not modifiable (i.e., it’s a constant) and that any
attempt to modify it is an error. For example,
private final int INCREMENT;
Declares a final (constant) instance variable INCREMENT of type int. Such variables can be initialized when
they’re declared. If they are not, they must be initialized in every constructor of the class. Initializing constants
in constructors enables each object of the class to have a different value for the constant. If a final variable is
not initialized in its declaration or in every constructor, a compilation error occurs.