Objects and Classes in Java
Objects and Classes in Java
In object oriented programming, object and class plays vital role in programming. These are the
two main pillars of OOP. Without object and class, we cannot create a program in Java. So, in
this section, we are going to discuss about objects and classes in Java.
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.
Characteristics 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.
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:
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.
Class in Java
1. 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.
2. 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.
3. 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.
4. 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.
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;
A variable created inside the class but outside the method is known as an instance variable. An
instance variable does not get memory at compile time; it gets memory at runtime when an
object or instance is created.
Each class instance has its own copy of instance variables, which means that changes made to
instance variables of one object do not affect the values of instance variables in other objects of
the same class. Moreover, setter methods and constructors can be used to initialize them. In
object-oriented programming, instance variables are crucial for encapsulating data within objects
since they are frequently used to represent the state or properties of objects.
Method in Java
In Java method is a block of code inside a class that's intended to carry out a certain function. To
provide a mechanism to interact with the state of an object and to encapsulate behaviour within
objects, methods are required.
Advantages of Methods
Code Reusability: Methods encourage code reusability by permitting the same block of code to
be used repeatedly inside a program. Once defined, a method can be called from any area of the
program where it is available.
Code Optimization: Methods allow for code optimization by enclosing intricate or repetitive
functionality into reusable components. The modularization of logic facilitates readability and
simplifies code maintenance.
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.
MyClass.java
int myField;
myField = value;
}
}
Output:
Value of myField: 10
In Java, 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 this example, we have created a Student class which has two data members id and name. We
are creating the object of the Student class by new keyword and printing the object's value.
File: Student.java
class Student{
//defining fields
String name;
System.out.println(s1.name);
}
Output:
null
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.
In real time development, we create classes and use it from another class. It is a better approach
than previous one. Let's see a simple example, where we are having main() method in another
class.
We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.
File: TestStudent1.java
//another class
class Student{
int id;
String name;
class TestStudent1{
System.out.println(s1.id);
System.out.println(s1.name);
Output:
null
Explanation
Initializing an object means storing data in the object. Let's see a simple example where we are
going to initialize the object through a reference variable.
File: TestStudent2.java
class Student{
int id;
String name;
class TestStudent2{
s1.id=101;
s1.name="Sonoo";
}
}
Output:
101 Sonoo.
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
class Student{
int id;
String name;
class TestStudent3{
//Creating objects
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
Output:
101 Sonoo
102 Amit
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method.
Here, we are displaying the state (data) of the objects by invoking the displayInformation()
method.
File: TestStudent4.java
class Student{
int rollno;
String name;
rollno=r;
name=n;
class TestStudent4{
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 Karan
222 Aryan
As we can see in the above figure, the object gets the memory in the heap memory area. The
reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 are
reference variables that refer to the objects allocated in memory.
File: ObjectConstructor.java
class Student {
int id;
String name;
// Constructor with parameters
this.id = id;
this.name = name;
student1.displayInformation();
student2.displayInformation();
Output:
Student ID: 1
Student ID: 2
Student Name: Jane Smith
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
id=i;
name=n;
salary=s;
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
Output:
There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
class Rectangle{
int length;
int width;
length=l;
width=w;
void calculateArea(){System.out.println(length*width);}
class TestRectangle1{
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
Output:
55
45
1. By new keyword
The most common way to create an object in Java is by using the new keyword followed by a
constructor.
For example: ClassName obj = new ClassName();. This allocates memory for the object and
calls its constructor to initialize it.
2. By newInstance() method
This method is part of the java.lang.Class class and is used to create a new instance of a class
dynamically at runtime. It invokes the no-argument constructor of the class.
3. By clone() method
The clone() method creates a copy of an existing object by performing a shallow copy. It returns
a new object that is a duplicate of the original object. For example: ClassName obj2 =
(ClassName) obj1.clone();.
4. By deserialization
Objects can be created by deserializing them from a stream of bytes. This is achieved using the
ObjectInputStream class in Java. The serialized object is read from a file or network, and then
the readObject() method is called to recreate the object.
5. By factory method
Factory methods are static methods within a class that return instances of the class. They provide
a way to create objects without directly invoking a constructor and can be used to encapsulate
object creation logic.
For example: ClassName obj = ClassName.createInstance().
Anonymous Object
If we have to use an object only once, an anonymous object is a good approach. For example:
c.fact(5);
new Calculation().fact(5);
class Calculation{
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
System.out.println("factorial is "+fact);
}
}
Output:
Factorial is 120
class Rectangle{
int length;
int width;
length=l;
width=w;
void calculateArea(){System.out.println(length*width);}
class TestRectangle2{
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
} }
Output:
55
45
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that we can create new classes that are built upon existing
classes. When we inherit methods from an existing class, we can reuse methods and fields of the
parent class. However, we can add new methods and fields in your current class also.
What is Inheritance?
Inheritance in Java enables a class to inherit properties and actions from another class, called a
superclass or parent class. A class derived from a superclass is called a subclass or child group.
Through inheritance, a subclass can access members of its superclass (fields and methods),
enforce reuse rules, and encourage hierarchy.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It
is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.
The extends keyword indicates that we are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class that is inherited is called a parent or superclass, and the new
class is called child or subclass.
Inheritance in Java
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
float salary=40000;
int bonus=10000;
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Types of inheritance in Java
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
void bark(){System.out.println("barking...");}
class TestInheritance{
d.bark();
d.eat();
}}
Output:
barking...
eating...
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Understanding Java Access Modifiers
Access Modifier within class within package outside package outside package
by subclass only
PRIVATE Y N N N
DEFAULT Y Y N N
PROTECTED Y Y Y N
PUBLIC Y Y Y Y
1) Private The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is a compile-time error.
class A{
A obj=new A();
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
class A{
private A(){}//private constructor
2) Default If you don't use any modifier, it is treated as default by default. The default modifier
is accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
//save by B.java
package mypack;
import pack.*;
class B{
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected The protected access modifier is accessible within package and outside the package
but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B extends A{
obj.msg();
}
}
Output:Hello
4) Public The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B{
obj.msg();
Output: Hello
The 'this' and the 'super' keywords are reserved words that are used in a different context.
Besides this, Java also provides this() and super() constructors that are used in the constructor
context. In this section, we will discuss the differences between this and super keyword and
this() and super() constructor, in Java.
A reserved keyword used to call the base class method or variable is known as a super keyword.
We cannot use the super keyword as an identifier. The super keyword is not only used to refer to
the base class instance but also static members too.
super() Constructor
The super() is mainly used for invoking base class member functions and constructors.
Let's take an example of both the super keyword and super() to understand how they work.
SuperExample1.java
package javaTpoint.MicrosoftJava;
class Animal{
//default constructor
Cat()
// default constructor
SuperExample1()
super();
new SuperExample1();
System.out.println("Inside Main");
Output:
this vs super in Java
In the main() method, we have made a statement new SuperExample1(). It calls the constructor
of the SuperExample1 class.
Inside the constructor, we have made statement super() which calls the constructor of its parent
class, i.e., Cat. In the constructor, we have made three statements:
When the second statement executes, the flow of the program jumps to Animal class to access
the value of its data members. After accessing it, the flow comes back to the Cat class
constructor and prints it. After that, the last statement executes and prints the value of the
variables of the current class.
After execution of the last statement of the Cat class, the flow comes back to the constructor of
class SuperExample1 and executes the remaining statements.
After completing the execution of the SuperExample1(), the flow comes back to the main()
method and executes the remaining statements.
Note: In order to use the super(), we have to make sure that it should be the first statement in the
constructor of a class. We can use it to refer only to the parent class constructor.
this keyword
It is a reserved keyword in Java that is used to refer to the current class object. It is a reference
variable through which the method is called. Other uses of this keyword are:
We can also use it for returning the current class instance from the method.
this() Constructor
The constructor is used to call one constructor from the other of the same class. Let's take an
example of both this keyword and this() to understand how they work.
ThisExample1.java
package javaTpoint.MicrosoftJava;
class ThisExample1 {
int x = 5;
staticinty = 10;
ThisExample1()
this(5);
ThisExample1(int x)
new ThisExample1();
System.out.println("Inside Main");
Output:
The following table describes the key difference between this and super:
this
super
In order to call the default constructor of the current class, we can use this keyword.
In order to call the default constructor of the parent class, we can use the super keyword.
It can be referred to from a static context. It means it can be invoked from the static context.
It can't be referred to from a static context. It means it cannot be invoked from a static context.
We can use it to access only the current class data members and member functions.
We can use it to access the data members and member functions of the parent class.
this()
super()