Introducing
CHAPTER 2 Classes,Objects
and Methods
JAVA CLASSES/OBJECTS
❖Java is an object-oriented programming language.
❖Everything in Java is associated with classes and objects, along with its
attributes and methods.
❖For example: in real life, a car is an object.
❖The car has attributes, such as weight and color, and methods, such as
drive and brake.
Classes and Objects in Java
❖ In object oriented programming, classes and objects play a vital role in
programming. These are the two main pillars of OOPs (Object-Oriented
Programming).
❖ Without class and object, we cannot create a program in Java.
What is an object in Java?
❖ An object is a real-word entity that has state and behaviour.
❖ In other words, an object is a tangible thing that can be touch
and feel, like a car or chair, etc. are the example of objects.
❖ The banking system is an example of an intangible object.
❖ Every object has a distinct identity, which is usually
implemented by a unique ID that the JVM uses internally for
identification.
Continued……
An object is an instance of a class. A class is a template or blueprint
from which objects are created. So, an object is the instance(result) of a
class.
Object Definitions:
❖ An object is a real-world entity.
❖ An object is a runtime entity.
❖ The object is an entity which has state and behavior.
❖ The object is an instance of a class.
Characteristics of an Object
❖ State: It represents the data (value) of an object.
❖ Behavior: It represents the behavior (functionality) of an object
such as deposit, withdraw, etc.
❖ Identity: An object's identity is typically implemented via a
unique ID. The ID's value is not visible to the external user;
however, it is used internally by the JVM to identify each object
uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white,
known as its state. It is used to write, so writing is its behavior.
What is a Class in Java?
❖ A class is a group of objects which have common properties. It is
a template or blueprint from which objects are created. It is a
logical entity. It can't be physical.
❖ A class in Java can contain:
Fields
❖ Variables stated inside a class that indicate the status of objects
formed from that class are called fields, sometimes referred to as
instance variables.
❖ They specify the data that will be stored in each class object.
❖ Different access modifiers, such as public, private, and protected,
can be applied to fields to regulate their visibility and usability.
Methods
❖ Methods are functions defined inside a class that includes the actions
or behaviors that objects of that class are capable of performing.
❖ These techniques allow the outside world to function and change the
object's state (fields).
❖ Additionally, methods can be void (that is, they return nothing) or
have different access modifiers.
❖ They can also return values.
Constructors
❖ Constructors are unique methods that are used to initialize class
objects.
❖ When an object of the class is created using the new keyword, they
are called with the same name as the class.
❖ Constructors can initialize the fields of an object or carry out any
additional setup that's required when an object is created.
Blocks
❖ Within a class, Java allows two different kinds of blocks: instance
blocks, commonly referred to as initialization blocks and static blocks.
❖ Static blocks, which are usually used for static initialization, are only
executed once when the class is loaded into memory.
❖ Instance blocks can be used to initialize instance variables and are
executed each time a class object is generated.
Nested Class and Interface
❖ Java permits the nesting of classes and interfaces inside other classes
and interfaces.
❖ The members (fields, methods) of the enclosing class are accessible to
nested classes, which can be static or non-static.
❖ Nested interfaces can be used to logically group related constants and
methods together because they are implicitly static.
Syntax of a Class
class <class_name>
{
field;
method;
}
new keyword
❖ The new keyword is used to allocate memory at runtime. All objects
get memory in the Heap memory area.
❖ In Java, an instance of a class (also referred to as an object) is
created using the new keyword.
❖ The new keyword dynamically allocates memory for an object of that
class and returns a reference to it when it is followed by the class
name and brackets with optional arguments.
main() method within the class
❖ the main() method can be declared in a class, which is typically done in
demonstration or basic programs.
❖ Having the main() method defined inside of a class allows a program to
run immediately without creating a separate class containing it.
❖ In real-world development, it is usual practice to organise Java classes
into distinct files and to place the main method outside of the class it is
intended to execute from.
❖ This strategy improves the readability, maintainability, and reusability of
the code.
Initializing Object in Java
There are the following three ways to initialize object in Java.
❖ By reference variable
❖ By method
❖ By constructor
Object Initialization through Reference Variable
Initializing an object means storing data in the object.
class Student
{
int id;
}
public class Demo
{
public static void main(String args[])
{
Student s1=new Student(); //Creating instance of Student class
[Link]=101; //assigning values through reference variable
[Link]([Link]);
}
}
Object Initialization through Method
public class Example
{
String name;
float price;
void method1(String n, float p)
{
name = n;
price = p;
}
void display()
{
[Link]("Software name is: " + name);
[Link]("Software price is: " + price);
}
public static void main(String args[])
{
Example e1=new Example();
e1.method1("Java", 0.0f);
[Link]();
}
}
Object Initialization through a
Constructor
class Student {
int id;
String name;
public Student(int id, String name) {
[Link] = id;
[Link] = name;
public void displayInformation() {
[Link]("Student ID: " + id+"Student Name: " + name);
public static void main(String[] args) {
Student student1 = new Student(1, "John Doe");
[Link]();
Create a class
To create a class, use the keyword class:
[Link]
Create a class named “First” with a variable x:
public class First {
int x = 5;
}
Create an object
Example
Create an object called "myObj" and print the value of x:
public class First {
int x = 5;
public static void main(String[] args) {
First myObj = new First();
[Link](myObj.x);
}
Multiple objects
public class Java1
{
int x = 5;
public static void main(String[] args) {
Java1 myObj1 = new Java1(); // Object 1
Java1 myObj2 = new Java1(); // Object 2
[Link](myObj1.x);
Using multiple classes
[Link]
public class First{
int x = 5;
}
[Link]
class Second {
public static void main(String[] args) {
First myObj = new First();
[Link](myObj.x);
}
}
Java class attributes
Example
Create a class called “First" with two attributes: x and
y:
public class First {
int x = 5;
int y = 3;
}
Multiple attributes
public class Java1 {
String fname = "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args) {
Java1 myObj = new Java1();
[Link]("Name: " + [Link] + " " +
[Link]);
[Link]("Age: " + [Link]);
}
Methods in Java
❖ The method in Java is a collection of instructions that performs a
specific task.
❖ It provides the reusability of code. We can also easily modify
code using methods.
What is a Method in Java?
❖ 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.
❖ It is used to achieve the reusability of code. We write a method
once and use it many times. We do not require to write code
again and again.
❖ It also provides the easy modification and readability of code,
just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.
Key Characteristics
❖ Reusability: Methods provides code reusability. Once a method
is defined, it can be called multiple times from various parts of
the program.
❖ Modularity: Methods help break down complex problems into
smaller, manageable pieces.
❖ Maintainability: With methods, updating and debugging code
becomes easier since changes in one part of the program do not
necessarily impact other parts.
Method Declaration
❖ The method declaration provides information about method
attributes, such as visibility, return-type, name, and arguments.
❖ It has six components that are known as method header, as we
have shown in the following figure.
❖ Method Signature: Every method has a method signature. It is a
part of the method declaration. It includes the method name and
parameter list.
Method Declaration
Access Specifier
Access Specifier: Access specifier or modifier is the access type of the
method. It specifies the visibility of the method. Java provides four types of
access specifier:
❖ Public: The method is accessible by all classes when we use public
specifier in our application.
❖ Private: When we use a private access specifier, the method is
accessible only in the classes in which it is defined.
❖ Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different
package.
❖ Default: 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.
❖ Return Type: Return type is a data type that the method returns. It may
have a primitive data type, object, collection, void, etc. If the method does
not return anything, we use void keyword.
❖ Method Name: It is a unique name that is used to define the name of a
method. It must be corresponding to the functionality of the method.
Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.
❖ Parameter List: It is the list of parameters separated by a comma and
enclosed in the pair of parentheses. It contains the data type and variable
name. If the method has no parameter, left the parentheses blank.
❖ Method Body: It is a part of the method declaration. It contains all the
actions to be performed. It is enclosed within the pair of curly braces.
Example
public class First {
static void myMethod() {
[Link]("Hello World!");
}
public static void Java1(String[] args) {
myMethod();
}
}
Types of Method
There are two types of methods in Java:
❖ Predefined Method
❖ User-defined Method
❖ In Java, predefined methods are the method that is already
defined in the Java class libraries is known as predefined
methods.
❖ It is also known as the standard library method or built-in
method.
❖ Some pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc.
❖ Each and every predefined method is defined inside a class. Such
as print() method is defined in the [Link] class.
❖ For example, print("Java"), it prints Java on the console.
Predefined Method
❖ In Java, predefined methods are the method that is already defined
in the Java class libraries is known as predefined methods.
❖ It is also known as the standard library method or built-in method.
❖ Some pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc.
❖ Each and every predefined method is defined inside a class. Such as
print() method is defined in the [Link] class.
❖ For example, print("Java"), it prints Java on the console.
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.
public class Example {
// Method definition
public int add(int a, int b) {
int sum = a + b; // Method body
return sum; // Return statement
}
}
Static keyword in Java
❖ The static keyword in Java is mainly used for memory management.
❖ The static keyword in Java is used to share the same variable or
method of a given class.
❖ The users can apply static keywords with variables, methods, blocks,
and nested classes.
❖ The static keyword belongs to the class rather than an instance of
the class.
❖ The static keyword is used for a constant variable or a method that is
the same for every instance of a class.
❖ Static classes in Java are allowed only for inner classes which are
defined under some other class.
❖ Static outer class is not allowed which means that we can't use static
keyword with outer class.
Refer Example Chapter2_doc.doc word document
Continued…
The static can be:
❖ Variable (also known as a class variable)
❖ Method (also known as a class method)
❖ Block
❖ Nested class
( example programs on static variable,static method , static block
refer chapter 2 code document)
Java Static Variable
❖ The static variable can be used to refer to the common property
of all objects (which is not unique for each object), for example,
the company name of employees, college name of students,
etc.
❖ The static variable gets memory only once in the class area at
the time of class loading.
❖ Static variables in Java are also initialized to default values if
not explicitly initialized by the programmer. They can be
accessed directly using the class name without needing to
create an instance of the class.
❖ Static variables are shared among all instances of the class,
meaning if the value of a static variable is changed in one
instance, it will reflect the change in all other instances as well.
Static Method
❖ A method that has static keyword is known as static method. In other
words, a method that belongs to a class rather than an instance of a
class is known as a static method.
❖ The main advantage of a static method is that we can call it without
creating an object. It can access static data members and also change
the value of it.
❖ It is used to create an instance method. It is invoked by using the class
name. The best example of a static method is the main() method.
Example of Static Method
public class Display
{
public static void main(String[] args)
{
show();
}
static void show()
{
[Link]("It is an example of static method.");
}
}
Example
public class Java1 {
static void myStaticMethod() {
[Link]("Static methods can be called without creating objects");
}
public void myPublicMethod() {
[Link]("Public methods must be called by creating objects");
}
public static void Java1(String[] args) {
myStaticMethod();
Java1 myObj = new Java1();
[Link]();
Static Block
❖ It is used to initialize the static data member.
❖ It is executed before the main() method at the time of class loading.
Example
public class Main{
Static
{
[Link]("static block is invoked");
}public static void main(String args[]){
[Link]("main() method is invoked");
}
}
Static Nested Classes
❖ A static nested class is declared with the static keyword.
❖ It behaves like a regular top-level class but is nested for packaging
convenience.
❖ Static nested classes cannot directly access non-static members of the
enclosing class.
Example
class A{
static class B{}//static nested class
}
Advantages of static Keyword
❖ Saves Memory: Instead of each object having its own copy of a variable,
static variables are shared across all objects of the class. This saves
memory because only one copy exists.
❖ Faster Access: Since static members belong to the class itself, we don't
need to create an object to use them. We can just call them using the
class name, making your code run faster.
❖ Great for Utility Methods: Some methods don't rely on object data, like
[Link]() or [Link](). Marking them static allows us to use
them directly without creating an object.
❖ Good for Constants: If a value never changes, like PI = 3.14159, making
it static final ensures that there's only one copy, making your code more
efficient.
Advantages of static Keyword
❖ Keeps Code Organized: Static methods help keep related logic in
one place. For example, if we have a DatabaseHelper class, its
connect() and disconnect() methods can be static, so we do not
have to create an object just to use them.
❖ Runs Automatically When the Class Loads: Static blocks
execute when the class is loaded. It is useful for setting up
configurations like initializing a database connection or loading files
before our program starts.
❖ Reduces Object Dependency: Static methods do not rely on an
object's state, making them useful in cases where creating an
object would be unnecessary or inefficient.
Method overloading
In Java, two or more methods may have the same name if they differ in
parameters (different number of parameters, different types of parameters,
or both). These methods are called overloaded methods and this feature is
called method overloading.
JAVA CONSTRUCTORS
❖ A constructor in Java is a special method that is used to initialize
objects.
❖ The constructor is called when an object of a class is created.
❖ It can be used to set initial values for object attributes
❖ Note that the constructor name must match the class name, and it
cannot have a return type (like void).
❖ Also note that the constructor is called when the object is created.
❖ All classes have constructors by default: if you do not create a class
Rules for Creating Java Constructor
There are following rules for defining a constructor:
❖ Constructor name must be the same as its class name.
❖ A Constructor must have no explicit return type.
❖ A Java constructor cannot be abstract, static, final, and
synchronized.
Note: We can use access modifiers while declaring a constructor. It
controls the object creation. In other words, we can have private,
protected, public or default constructor in Java.
Types of Constructors
In Java, constructors can be divided into three types:
❖ No-Arg Constructor
❖ Parameterized Constructor
❖ Default Constructor
Java Default Constructor
❖ If we do not create any constructor, the Java compiler
automatically creates a no-arg constructor during the
execution of the program.
❖ This constructor is called the default constructor.
❖ the Java compiler automatically creates the default
constructor.
❖ The default constructor initializes any uninitialized instance
Example
class Bike{
//creating a default constructor
Bike(){[Link]("Bike is created");}
}
public class Main{
//main method
public static void main(String args[]){
//calling a default constructor
Bike b=new Bike();
}
Java No-Arg Constructors
Similar to methods, a Java constructor may or may not have any
parameters (arguments).
If a constructor does not accept any parameters, it is known as a no-
argument constructor.
For example,
Constructor() {
// body of the constructor
EXAMPLE(No parameter constructor)
class Demo {
private String name;
// constructor
Demo() { //no-args constructor
[Link]("Constructor Called:");
name = "Programiz";
}
public static void main(String[] args) {
Demo obj = new Demo();
[Link]("The name is " + [Link]);
}
}
Java Parameterized Constructor
❖ A Java constructor can also accept one or more
parameters. Such constructors are known as
parameterized constructors (constructors with
parameters).
Constructor(int a,int b){
// body of the constructor
EXAMPLE
public class First
{
int x;
public First(int y) { //parameterized constructor
x = y;
}
public static void Java1(String[] args) {
First myObj = new First(5);
[Link](myObj.x);
}
}
EXAMPLE
public class First {
int modelYear;
String modelName;
public First(int year, String name) {//parameterized constructor
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
First myCar = new First(1969, "Mustang");
[Link]([Link] + " " + [Link]);
}
EXAMPLE
class Java1 {
String languages;
// constructor accepting single value
Java1(String lang) {
languages = lang;
[Link](languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Java1 obj1 = new Java1("Java");
Java1 obj2 = new Java1("Python");
Java1 obj3 = new Java1("C");
}
}
EXAMPLE (Default Constructor)
class Main {
int a;
boolean b;
public static void main(String[] args) {
// calls default constructor
Main obj = new Main();
[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
Constructor overloading
❖ In Java, constructor overloading means to define multiple constructors
but with different signatures.
❖ Constructor overloading is a technique of having more than one
constructor in the same class with different parameter lists.
Refer chapter2 word document
Copy Constructor
❖ In Java, a copy constructor is a special type of constructor that
creates an object using another object of the same Java class. It
returns a duplicate copy of an existing object of the class.
❖ The primary use case of a copy constructor is to create a new
object with the same state as an existing object. It is particularly
useful in scenarios where we need to duplicate an object while
maintaining its integrity.
Ex: refer chapter 2 code document
Constructor chaining
❖ In constructor chain, a constructor is called from another constructor in
the same class this process is known as constructor chaining.
We can achieve constructor chaining in two ways:
❖ Within the same class: If the constructors belong to the same class, we
use this
❖ From the base class: If the constructor belongs to different classes
(parent and child classes), we use the super keyword to call the
constructor from the base class.
Syntax
Java Garbage Collection
❖ In java, garbage means unreferenced objects.
❖ Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.
❖ To do so, we were using free() function in C language and
delete() in C++. But, in java it is performed automatically. So,
java provides better memory management.
Advantage of Garbage Collection
❖ It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
❖ It is automatically done by the garbage collector(a part of JVM) so
we don't need to make extra efforts.
How can an object be unreferenced?
❖ By nulling the reference
❖ By assigning a reference to another
❖ By anonymous object etc.
❖ By nulling a reference:
Employee e=new Employee();
e=null;
❖ By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for
garbage collection
❖ By anonymous object:
new Employee();
finalize() method
❖ The finalize() method is invoked each time before the object is
garbage collected.
❖ This method can be used to perform cleanup processing. This
method is defined in Object class as:
❖ protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that
are created by new keyword. So if you have created any object
without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
gc() method
❖ The gc() method is used to invoke the garbage collector to
perform cleanup processing. The gc() is found in System
and Runtime classes.
public static void gc(){}
Reference Variable in Java
When we create an object (instance) of class then space is reserved
in heap memory.
Demo D1 = new Demo();
this keyword in Java
There can be a lot of usage of Java this keyword. In Java, this is a
reference variable that refers to the current object.
this: to refer current class
instance variable
Let's see the example
Refer code in word Chapter2_docdocument
this: to invoke current class
method
❖ You may invoke the method of the current class by using the
this keyword.
❖ If you don't use the this keyword, compiler automatically adds
this keyword while invoking the method.
Refer code in word Chapter2_docdocument
this() : to invoke current class
constructor(used in constructor chainig)
❖ The this() constructor call can be used to invoke the
current class constructor.
❖ It is used to reuse the constructor.
❖ In other words, it is used for constructor chaining.
Refer code in word Chapter2_docdocument
Access Modifiers in Java
❖ Access modifiers in Java are keywords that control the accessibility of
classes, methods, and variables.
❖ They are fundamental to object-oriented programming as they help
enforce encapsulation, a core principle restricting direct access to some
of an object's components.
❖ Java provides four main types of access modifiers: `public`, `private`,
`protected`, and the default access (no modifier).
❖ The `public` modifier allows elements to be accessible from any other
class in the application, regardless of the package
Access Modifiers in Java
`Protected` allows access within the same package or in subclasses,
which might be in different packages.
Lastly, the default access (no modifier) limits the visibility to classes
within the same package.
Different Types of Access Modifiers
private
❖ The private access modifier is the most restrictive level of access control.
❖ When a member (be it a field, method, or constructor) is declared private,
it can only be accessed within the same class.
❖ No other class, including subclasses in the same package or different
packages, can access the member.
private
This modifier is typically used for sensitive data that should be hidden
from external classes.
Example:
public class Person {
private String name;
private String getName() {
return [Link];
}
}
In this example, the name attribute and the getName() method are
only accessible within the Person class
private
When variables and methods are declared private, they cannot be accessed
outside of the class.
Example
class Data {
private String name;
}
public class Main {
public static void main(String[] main){
Data d = new Data();
[Link] = "java";
In the above example, we have declared a private variable
named name. When we run the program, we will get the following
error:
jav[Link] error: name has private access in Data
[Link] = "java";
^
1 error
ERROR!
error: compilation failed
The error is generated because we are trying to access the
private variable of the Data class from the Main class.
How to access private variable?
Example
Refer Chapter_doc word document
default (no modifier
❖ When no access modifier is specified, Java uses a default access level,
often called package-private.
❖ This means the member is accessible only within classes in the same
package. It is less restrictive than private but more restrictive than
protected and public.
Example:
class Log {
void display() {
[Link]("Displaying log information");
}
}
default Access Modifier
The Logger class has the default access modifier.
And the class is visible to all the classes that belong to the
defaultPackage package.
However, if we try to use the Logger class in another class outside
of defaultPackage, we will get a compilation error.
If we do not explicitly specify any access modifier for classes,
methods, variables, etc, then by default the default access modifier
is considered
default Access Modifier
Example
package defaultPackage;
class Logger {
void message()
[Link]("This is a message");
}
protected
❖ The protected access modifier is less restrictive than private
and default.
❖ Members declared as protected can be accessed within the
same package or in subclasses in different packages.
❖ This is particularly useful in cases where you want to hide a
member from the world but still make it available to child
classes.
protected
Example:
public class Animal {
protected String type;
protected void displayType() {
[Link]("Type: " + type);
}
}
Here, the type attribute and the displayType() method can be accessed
within all classes in the same package and in any subclass of Animal, even
if those subclasses are in different packages.
protected
❖ When methods and data members are declared protected, we
can access them within the same package as well as from
subclasses.
For example,
class Animal {
// protected method
protected void display() {
[Link]("I am an animal");
class Dog extends Animal {
public static void main(String[] args) {
// create an object of Dog class
Dog dog = new Dog();
// access protected method
[Link]();
}
}
protected
In the above example, we have a protected method named display()
inside the Animal class. The Animal class is inherited by the Dog class.
We then created an object dog of the Dog class. Using the object we tried
to access the protected method of the parent class.
Since protected methods can be accessed from the child classes, we are
able to access the method of Animal class from the Dog class.
Note: We cannot declare classes or interfaces protected in Java.
public
The public access modifier is the least restrictive and specifies that the
member can be accessed from any other class anywhere, whether within or
in a different package.
This access level is typically used for methods and variables that must be
available consistently to all other classes.
Example:
public class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}
}