chapter 2 Class and object2017
chapter 2 Class and object2017
03/11/2025 2
Defining a class
Java provides a reserved keyword class to define a class. The keyword must be followed by the
class name. Inside the class, we declare methods and variables.
In general, class declaration includes the following in the order as it appears:
• Modifiers: A class can be public or has default access.
• Class keyword: The class keyword is used to create a class.
• Class name: The name must begin with an initial letter (capitalized by convention).
• Superclass (if any): The name of the class's parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
• Body: The class body surrounded by braces, { }.
Syntax:
<access specifier> class class_name
{
// member variables
// class methods
}
03/11/2025 3
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
...
type methodnameN(parameter-list) {
// body of method
}
03/11/2025 4
What is an object in Java
There are 3 ways to initialize
object in Java.
Object 1. By reference variable
A software bundle that has State and Behaviour. 2. By method
An Object's state is stored in variables called fields. 3. By constructor
An Object's behaviour is defined by its methods. Example: initialize by reference
An object is the instance(result) of a class. class Student{
int id;
An object is a real-world entity. String name;
An object is a runtime entity. }
class TestStudent2{
Example 1: Dogs:
public static void main(String args[]){
States: name, color, breed, and “is hungry?”. Student s1=new Student();
s1.id=101;
Behaviors: bark, run, and wag tail
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
} }
03/11/2025 5
Creating an Object
An object in Java is essentially a block of memory that contains space to store all the instance variables.
Creating an object also known as instantiating an object.
The new operator creates an object of the specified class and returns a reference to that object.
Syntax for object creation:
classname objectname; //declares a variable to hold the object reference
objectname = new classname( ); // Assigns the object reference to the variable
So basically an object is created from a class. In Java, the new key word is used to create new objects.
There are three steps when creating an object from a class:
♦ Declaration:- A variable declaration with a variable name with an object type.
♦ Instantiation:- The 'new' keyword is used to create the object.
♦ Initialization:- The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
03/11/2025 6
Cont…;
Example:
Rectangle R1 = new Rectangle();
R1 is a reference to Rectangle
Rectangle object object
03/11/2025 7
Adding Variables (Fields)
Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called instance variables (member variables) because they are created when an object of
Example:
class Rectangle
int length;
int width;
03/11/2025 8
Types of Variables
There are three types of variables in Java:-
1) Local Variable: A variable declared and used inside the body of the method
definitions.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
It is used to define attributes or state for a particular objects.
The data, or variables, defined within a class are called instance variables.
The methods and variables defined within a class are called members of the
class.
It acted upon and accessed by the methods defined for that class.
3) Static variable
03/11/2025 A variable that is declared as static is called a static variable. It cannot
9 be
Declaring Variables
To use any variable in a Java program, you must first declare it. Variable declarations
consist of a type and a variable name:
int myAge;
Variable names
• In Java can start with a letter, an underscore (_), or a dollar sign ($).
• A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and
underscore(_) or a dollar sign ($).
• They cannot start with a number.
• After the first character, your variable names can include any letter or
number.
Variable Type: The variable type can be one of three things:-
• One of the eight basic primitive data types
03/11/2025 10
• The name of a class
Adding Methods
A class with only data fields (and without methods that operate on that data) has no life.
Methods are declared inside the body of the class but immediately after the declaration of
the instance variables.
The general form of a method declaration is:
type methodname(parameter-list)
{
method-body;
}
03/11/2025 11
Method declaration has four parts:
• Data type: The type specifies the type value the method would return. It could be void type, if the method
does not return any value.
• Parameter-list: is always enclosed in parenthesis and contains variable names and types of all the values we
want to give to the method as input.
Methods which act upon instance variables of a class are called instance methods.
Any modifications to instance variable in one object will not affect the instance variable of other objects.
Instance methods can read and act upon static variables also.
03/11/2025 12
Class - Example
class Rectangle
{
int length, width;
void getData(int x, int y) // A method with two parameter
{
length=x;
width=y;
}
int rectArea() // A method with no parameter
{
return length*width;
}}
03/11/2025 13
Methods and Message
Message
Method: Purchase ()
{
address = 1, Robinson Road "Benjamin", "stock", "address", "date" are arguments of the
03/11/2025
• takeOrder is a method call on Sean; 15
Constructors
Constructors are a special kind of methods that are invoked to construct objects.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
Java supports a special type of method, called a constructor, that enables an object to initialize itself when
it is created.
Call the constructor(s) preceding it with the new keyword.
03/11/2025 16
Rules with Constructors
There are rules defined for the constructor.
Class name and constructor name should be the same. .
Constructors have no return type
Constructors should be public.
Constructors cannot be inherited.
They can be overloaded.
Constructors are invoked using the new operator when an object is created. Constructors play the
role of initializing objects.
A Java constructor cannot be abstract, static, final, and synchronized
03/11/2025 17
Types of Java constructors
03/11/2025 18
Default Constructor Parameterized Constructor
Class Box
{ Class Box
double width;
{
double height; double width;
double depth; double height;
Box() // default constructor double depth;
Box(double w, double h, double d)
{ {
System.out.println("Constructing
width = w;
Box"); height = h;
width = 10; height = 10; depth =
depth = d;
10; }
}
double volume()
{
double volume()
return width * height * depth;
{ }
return width * height * depth; }
}
03/11/2025 19
this Keyword
The this keyword is the name of a reference that refers to an object itself.
One common use of the this keyword is reference a class’s hidden data fields.
Another common use of the this keyword to enable a constructor to invoke another constructor of the
same class.
Can be used by any object to refer to itself in any class method.
Typically used to class LightSwitch
{
► avoid variable name collisions boolean on;
LightSwitch(boolean on) {
this.on = on;
}
}
03/11/2025 20
Cascading Constructors
A constructor can call another constructor with this(arguments)
class LightSwitch
{
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
03/11/2025 21
Parameter Passing
While working under calling process, arguments is to be passed. These should be in the same order as their
respective parameters in the method specification.
Parameters can be passed
• By value : Calling a method with a parameter.Through this the argument value is passed to the parameter
• This method copies the value of an argument into the formal parameter of the subroutine.
• Therefore, changes made to the parameter of the subroutine have no effect on the argument. It's
to pass primitive data types values.
• By Reference:-
• In this method, a reference to an argument (not the value of the argument) is passed to the
parameter.
• To pass objects, changes made to the parameter will affect the argument used to call the
subroutine
03/11/2025 22
Example-1: Passing by value: change will no happen to instance variables ‘name’ and ‘idno’!
03/11/2025 23
Example-1: Passing by reference: change will happen to instance variables ‘name’ and
‘idno’!
03/11/2025 24
Access Modifiers
Access Modifiers are keywords that can be used to control the visibility of fields, methods, and constructors in
a class.
In Java, the access modifiers are used for restricting the scope of a class and its data members, member
function, and constructor
It used to specify the access levels for classes, variable, methods, and constructor.
They are also known as visibility modifier.
Access modifiers play an important in designing Java programs and Java applications.
Java has the following access modifiers:
1. Private
2. Protected
3. Public
4. Default
03/11/2025 25
Default Access Modifier
• When we do not use any access specifier in the method declaration, Java uses default access specifier by
default.
• It is visible only from the same package only.
• The default modifier is accessible only within package
• It provides more visibility than private access modifier.
• But, it is more restricted than protected and public access modifiers.
• The class, data members, and member functions that we defined without using access modifiers can be
accessed only within the same package.
• Outside of the current package, we cannot use the classes and methods.
03/11/2025 26
Example
03/11/2025 27
Suppose, there are two packages, say pack 1
and pack 2.
Here, Class A and Class B are declared as
default and we are accessing the Class A from
outside its package, since Class A is default, so
it cannot be accessed from any outside
package.
03/11/2025 28
Private Access Modifier
The private access modifier is accessible only within class.
Methods, Variables and Constructors that are declared private can only be accessed within the declared
class itself.
Private access modifier is the most restrictive access level.
Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in
the class.
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside
the class.
03/11/2025 29
Public Access Modifier
A class, method, constructor, interface etc declared public can be accessed from any other class.
However if the public class we are trying to access is in a different package, then the public class still need
to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.
We can access the methods and variables of a class from anywhere in the program, which is declared as
public.
In simple words, no restriction is allowed on the scope of public data members.
03/11/2025 30
Protected Access Modifier
The protected access modifier is accessible within package and outside the package but through
inheritance only.
Variables, methods and constructors which are declared protected in a superclass can be accessed only by
the subclasses in other package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces.
Methods, fields can be declared protected, however methods and fields in a interface cannot be declared
protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a
nonrelated class from trying to use it.
03/11/2025 31
03/11/2025 32
Access Control and Inheritance:
The following rules for inherited methods are enforced:
♦ Methods declared public in a superclass also must be public in all subclasses.
♦ Methods declared protected in a superclass must either be protected or public in
subclasses; they cannot be private.
♦ Methods declared without access control (no modifier was used) can be declared
more private in subclasses.
♦ Methods declared private are not inherited at all, so there is no rule for them.
03/11/2025 33
Encapsulation
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public
methods.
If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields
within the class.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the
code of others who use our code.
With this feature Encapsulation gives maintainability, flexibility and extensibility to our code
Benefits of encapsulation
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data.
A class can change the data type of a field and users of the class do not need to change any of their code.
03/11/2025 34