Chapter 5
Classes, Objects and Methods
The classes and objects are core part of Java Programming language. Java code is
contained in either a class or an Interface.
Here we will be discussing mainly about classes. Java is an object-oriented
programming language. Anything we wish to represent in java program must be
encapsulated in a class that defines the state and behaviour of program
components known as objects. Classes create objects and objects use methods to
communicate between them.
Java Class
A class is a user defined blueprint or template for which objects
are created. Before we create an object, we first need to define the class.
we can create many objects from a class.
A class in Java is a set of objects which shares common
characteristics and common properties. It is a user-defined blueprint or
prototype from which objects are created.
For example, Student is a class while a particular student named
Ravi is an object.
Properties of Java Classes
Class is not a real-world entity. It is just a template or blueprint or
prototype from which objects are created.
Class does not occupy memory.
Class is a group of variables of different data types and a group of
methods.
A Class in Java can contain:
o Data member
o Method
o Constructor
o Nested Class
Page | 1
Interface
o
Defining a Class
We define a class using a keyword called 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:
1. Access specifier or Modifiers: We can access Java classes
using any access modifiers such as public, private, protected
and default.
2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by
convention).
4. 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. While using inheritance we use this.
5. Interfaces (if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
6. Body: The class body surrounded by braces, { }.
Syntax:
[access modifier]class Classname [extends
superclassname]
{
//class body containing variables
and methods
[variables declaration] //optional
[Methods declaration] //optional
}
Everything that is enclosed in square brackets
is optional.
Page | 2
Example:
Rules for Defining a Class:
1. The class names start with a capital letter followed by lower case letters.
2. It must be a legal java identifier.
3. There can be only one public class per source code file. This means that we
can have only one public class and as many as non-public classes in single
source file.
4. The name of the .java file must match with the public class. If there is no
public class, then we can give any name
5. A source file may have any number of non-public classes.
6. If a class is to be defined in a package, then the package statement must be
the first statement in the source file.
Page | 3
Adding Variables to a Class:
We can declare the variables inside the class. The variables inside a class are of
two types: The class variables and Instance variables.
o The class variables will always have the modifier static in front of them. The
class variables are also called as Static variables.
Ex: static int age=30;//a class variable
o The same variable defined as an instance variable would be:
Ex: int age=30; // an instance variable
Note: The instance variables and class variables can also be initialized with values,
if not initialized, it takes default value.
Java Methods and Adding Methods to Class:
The methods are functions that manipulate the data defined by
the class. A method is a block of code or collection of statements or a
set of code grouped together to perform a certain task or operation.
Code reusability, readability and easier to debug can be considered as
the advantages of Java Methods. The method is executed only when
we call or invoke it. All methods in Java must belong to a class. The
method needs to be called for use its functionality. There can be
three situations when a method is called:
A method returns to the code that invoked it when:
It completes all the statements in the method.
It reaches a return statement.
Throws an exception.
The general syntax of defining a method is
Page | 4
Syntax:
Key Components of a Method Declaration
Modifier: It specifies the method’s access level (e.g., public, private,
protected, or default).
Return Type: The type of value returned, or void if no value is returned.
Method Name: It follows Java naming conventions; it should start with a
lowercase verb and use camel case for multiple words.
Parameters: A list of input values (optional). Empty parentheses are used if
no parameters are needed.
Exception List: The exceptions the method might throw (optional).
Method Body: It contains the logic to be executed (optional in the case of
abstract methods).
Page | 5
Types of Methods in Java
1. Predefined Method
Predefined methods are the method that is already defined in the Java class
libraries. It is also known as the standard library method or built-in method.
Example:
[Link]() // returns random value
[Link]() // return pi value
2. User-defined Method
The method written by the user or programmer is known as a user-defined
method. These methods are modified according to the requirement.
Example:
greet();
setName();
Creating Objects:
An object is created by instantiating a class. Process of creating an
object of a class is called as instantiation and the created object is
called as an Instance of a class.
It is Run time entity
It has state and behaviour.
It is an instance of a class.
An object in java is essentially a block of memory that
contains all the space to store instance variable.
Objects in java are created using the new operation or operator or
keyword.
The new operator creates an object of the specified class and
returns a reference to that object.
Page | 6
The general form of creating an object is:
Syntax:
<class name> <reference_variable> = new <classname>([arguments]);
Where,
o classname is the name of the class
o reference_variable is a variable which refer to an object
o new is an operator to create an object
o arguments are optional and they determine the initial values of instance
variables of that object
Accessing Class Members:
Class consists of variables and methods. Once an object is created, we can access
the members of the class using dot (.) operator. The dot operator links the name of
an object with the name of a member.
The general form of accessing class member is:
Syntax:
To access Variables: object_name.variable;
To access Methods: object_name.method();
Page | 7
Constructors:
A constructor is a special method that is called when an object of a class is
created. It is used to initialize newly created objects and has the same name as the
class.
Syntax:
Class ClassName
{
ClassName()
{
//body of the constructor
}
}
Key Features of Constructors:
It does not have a return type (not even void).
Name must match with the name of the class.
Any access modifiers can be used.
Can be overloaded
Cannot be called from methods
Can be called from other constructors.
Static key word cannot be applied to constructors.
It is automatically called when an object is created.
It is mainly used to initialize instance variables.
If no constructor is defined, Java provides a default constructor.
Page | 8
Types of Constructors in Java
Default Constructor
Parameterized Constructor
No-Argument Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the
compiler does not create a default constructor. It is taken out. It is being overloaded
and called a parameterized constructor. The default constructor changed into the
parameterized constructor. But Parameterized constructor can’t change the default
constructor. The default constructor can be implicit or explicit.
Implicit Default Constructor: If no constructor is defined in a class, the Java
compiler automatically provides a default constructor. This constructor doesn’t take
any parameters and initializes the object with default values, such as 0 for
numbers, null for objects.
Explicit Default Constructor: If we define a constructor that takes no parameters,
it’s called an explicit default constructor. This constructor replaces the one the
compiler would normally create automatically. Once you define any constructor
(with or without parameters), the compiler no longer provides the default constructor
for you.
Example:
class Car {
// Default constructor
Car() {
[Link]("Car is created!");
}
public static void main(String[] args) {
Car myCar = new Car(); // Constructor is called automatically
}
}
Output:
Car is created!
Page | 9
2. Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we
want to initialize fields of the class with our own values, then use a parameterized
constructor.
Example:
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student("Alice", 20); // Passing values
[Link]();
}
}
Output:
Name: Alice, Age: 20
3. No-Argument Constructor
A constructor may or may not have any parameters (arguments). Constructor with
no arguments is known as no-arg constructor.
Example of a No-Argument Constructor
class Car {
// No-argument constructor
Car() {
[Link]("A new car is created!");
Page | 10
}
public static void main(String[] args) {
Car myCar = new Car(); // Calls the constructor automatically
}
}
Output:
A new car is created!
No-Argument Constructor with Instance Variables
It initializes instance variables with default values.
class Student {
String name;
int age;
// No-argument constructor
Student() {
name = "Unknown";
age = 18;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student(); // Calls the no-argument constructor
[Link]();
}
}
Output:
Name: Unknown, Age: 18
Constructor Overloading
Constructor overloading means having multiple constructors in the same class
with the same name but different parameter lists (number or type of parameters).
Rules for Constructors in Java
Here are some rules for constructors in Java:
Page | 11
Name: The constructor's name must be the same as the class name.
Return type: Constructors cannot have a return type, even void.
Modifiers: Constructors cannot be static, synchronized, abstract, or final.
Inheritance: Constructors are not inherited by subclasses, but the constructor
of the superclass can be called from the subclass.
Access modifiers: Access modifiers can be used in constructor declaration to
control its access.
Automatic invocation: When an object is created, the constructor is
automatically called.
Private constructors: Constructors can be private to prevent the outside
world from creating a new instance of a class.
Page | 12
Example: Constructor Overloading in Action
class Person {
String name;
int age;
// Default constructor
Person() {
name = "Unknown";
age = 18;
}
// Constructor with one parameter
Person(String n) {
name = n;
age = 18;
}
// Constructor with two parameters
Person(String n, int a) {
name = n;
age = a;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Person p1 = new Person(); // Calls default constructor
Person p2 = new Person("Alice"); // Calls constructor with one
parameter
Person p3 = new Person("Bob", 25); // Calls constructor with two
parameters
[Link]();
[Link]();
[Link]();
}
}
Output:
Name: Unknown, Age: 18
Name: Alice, Age: 18
Name: Bob, Age: 25
Difference between Default Constructor and parameterized Constructor
Page | 13
Difference between Constructor and method
Page | 14
Using this keyword
In Java, ‘this’ is a reference variable that refers to the current object, or can
be said “this” in Java is a keyword that refers to the current object instance.
It can be used to call current class methods and fields, to pass an instance of
the current class as a parameter, and to differentiate between the local and
instance variables.
Methods to use ‘this’ in Java
Following are the ways to use the ‘this’ keyword in Java mentioned below:
Using the ‘this’ keyword to refer to current class instance variables.
Using this() to invoke a constructor from another constructor
Using ‘this’ keyword to return the current class instance
Using ‘this’ keyword as the method parameter
Using ‘this’ keyword to invoke the current class method
Using ‘this’ keyword as an argument in the constructor call
Using ‘this’ keyword to resolve the name conflicts.
Page | 15
1. Using ‘this’ keyword to refer to current class instance variables
Page | 16
2. Using this() to invoke a constructor from another constructor
Output:
Page | 17
The process of calling the constructors from other constructors is called as
Constructor Chaining.
Method Overloading:
In Java two or more methods Within the same class can have the same name
but with different number of arguments and type of arguments. This is called
as method overloading.
Method overloading in Java is also known as Compile-time Polymorphism,
Static Polymorphism, or Early binding.
Each method has a signature which is nothing but the name of the method
under the number of arguments and type of the arguments.
Java considers two methods different from each other if the signatures are
different.
Two methods in the same class can have the same name if they have
different numbers or different types of arguments.
Method overloading is one of the ways that Java implements polymorphism
Example
Page | 18
Note: Read static methods, static variables and static blocks from text
book.
*************************************************************
Page | 19