Java Classes
A class in Java is a set of objects that share 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 a prototype from which
objects are created.
• Class does not occupy memory.
• A 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
o Interface
Class Declaration in Java
access_modifier class <class_name>
data member;
method;
constructor;
nested class;
interface;
Components of Java Classes
In general, class declarations can include these components, in order:
• Modifiers: A class can be public or has default access (Refer this for details).
• Class keyword: Class keyword is used to create a class.
• Class name: The name should 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.
• 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.
• Body: The class body is surrounded by braces, { }.
Java Constructors
Java constructors or constructors in Java is a terminology used to construct something in our
programs. A constructor in Java is a special method that is used to initialize objects when they are
created. It is automatically called when an object is instantiated using the new keyword. It can be
used to set initial values for object attributes.
Key Features of Constructors:
• Same Name as the Class: A constructor has the same name as the class in which it is defined.
• No Return Type: Constructors do not have any return type, not even void. The main purpose
of a constructor is to initialize the object, not to return a value.
• Automatically Called on Object Creation: When an object of a class is created, the constructor
is called automatically to initialize the object’s attributes.
• Used to Set Initial Values for Object Attributes: Constructors are primarily used to set the
initial state or values of an object’s attributes when it is created.
Example: This program demonstrates how a constructor is automatically called when an object is
created in Java.
// Java Program to demonstrate
// Constructor
import java.io.*;
// Driver Class
class A {
// Constructor
Geeks()
super();
System.out.println("Constructor Called");
// main function
public static void main(String[] args)
A a1 = new A();
Output
Constructor Called
Note: It is not necessary to write a constructor for a class. It is because the java compiler creates a
default constructor (constructor with no arguments) if your class doesn’t have any.
How Java Constructors are Different From Java Methods?
The below table demonstrates the key difference between Java Constructor and Java Methods.
Features Constructor Method
Constructors must have the same name as the Methods can have any valid
Name class name name
Methods have the return type or
Constructors do not return any type
void if does not return any value.
Return Type
Constructors are called automatically with new
Methods are called explicitly
Invocation keyword
Methods are used to perform
Constructors are used to initialize objects
Purpose operations
Now let us come up with the syntax for the constructor being invoked at the time of object or
instance creation.
class A{
…….
// A Constructor
A() {
…….
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
A obj = new A();
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an
overloaded constructor), if you don’t type in the call to super in your constructor the compiler will
provide you with a non-argument call to super at the first line of your code, the super constructor must
be called to create an object:
Note: If you think your class is not a subclass it actually is, every class in Java is the subclass of a
class object even if you don’t say extends object in your class definition.
Why Do We Need Constructors in Java
Constructors play a very important role, it ensures that an object is properly initialized before use.
What happens when we don’t use constructors:
Without constructors:
• Objects might have undefined or default values.
• Extra initialization methods would be required.
• Risk of improper object state
When Java Constructor is called?
Each time an object is created using a new() keyword, at least one constructor (it could be the default
constructor) is invoked to assign initial values to the data members of the same class. Rules for writing
constructors are as follows:
• The constructor(s) of a class must have the same name as the class name in which it resides.
• A constructor in Java can not be abstract, final, static, or Synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e which other
class can call the constructor.
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so primarily there are three types of
constructors in Java are mentioned below:
• Default Constructor
• Parameterized Constructor
• Copy 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: This program demonstrates the use of a default constructor, which is automatically called
when an object is created.
// Java Program to demonstrate
// Default Constructor
import java.io.*;
// Driver class
class A {
// Default Constructor
A() {
System.out.println("Default constructor"); }
// Driver function
public static void main(String[] args)
A a1 = new A();
Output
Default constructor
Note: Default constructor provides the default values to the object like 0, null, false etc. depending on
the type.
2. Parameterized Constructor in Java
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: This program demonstrates the use of a parameterized constructor to initialize an object’s
attributes with specific values.
// Java Program for Parameterized Constructor
import java.io.*;
class A {
// data members of the class.
String name;
int id;
A(String name, int id) {
this.name = name;
this.id = id;
class B
public static void main(String[] args)
// This would invoke the parameterized constructor.
A a1 = new A("Avinash", 68);
System.out.println("AName :" +a1.name
+ " and AId :" + a1.id);
Output
AName :Avinash and BId :68
Remember: Does constructor return any value?
There are no “return value” statements in the constructor, but the constructor returns the current class
instance. We can write ‘return’ inside a constructor.
3. Copy Constructor in Java
Unlike other constructors copy constructor is passed with another object which copies the data
available from the passed object to the newly created object.
Note: In Java,there is no such inbuilt copy constructor available like in other programming languages
such as C++, instead we can create our own copy constructor by passing the object of the same class
to the other instance(object) of the class.
Example: This example, demonstrates how a copy constructor can be used to create a new object by
copying the values of another object’s attributes.
// Java Program for Copy Constructor
import java.io.*;
class A {
// data members of the class.
String name;
int id;
// Parameterized Constructor
A(String name, int id)
this.name = name;
this.id = id;
// Copy Constructor
A(A obj2)
this.name = obj2.name;
this.id = obj2.id;
class A {
public static void main(String[] args)
// This would invoke the parameterized constructor.
System.out.println("First Object");
A a1 = new A("Avinash", 68);
System.out.println("AName :" + a1.name
+ " and AId :" + a1.id);
System.out.println();
// This would invoke the copy constructor.
A a2 = new A(a1);
System.out.println(
"Copy Constructor used Second Object");
System.out.println("AName :" + a2.name
+ " and AId :" + a2.id);
Output
First Object
AName :Avinash and AId :68
Copy Constructor used Second Object
AName :Avinash and AId :68
Constructor Overloading
When we create more than one constructors in same class provided they have different umber of
arguments / different type of argument.
package contructor;
public class B {
B(){
System.out.println(1);
B(int x){
System.out.println(10);
public static void main(String[] args) {
B b1=new B();
B b2=new B(100);
}
}
Output
Constructor Chaining
Constructor chaining is the process of calling one constructor from another constructor with respect
to current object.
One of the main use of constructor chaining is to avoid duplicate codes while having multiple
constructor (by means of constructor overloading) and make code more readable.
Prerequisite - Constructors in Java
Constructor chaining can be done in two ways:
• Within same class: It can be done using this() keyword for constructors in the same class
• From base class: by using super() keyword to call the constructor from the base class.
Constructor chaining occurs through inheritance. A sub-class constructor’s task is to call super class’s
constructor first. This ensures that the creation of sub class’s object starts with the initialization of the
data members of the superclass. There could be any number of classes in the inheritance chain. Every
constructor calls up the chain till the class at the top is reached.
Why do we need constructor chaining?
This process is used when we want to perform multiple tasks in a single constructor rather than
creating a code for each task in a single constructor we create a separate constructor for each task and
make their chain which makes the program more readable.
Example:
package constructor_chaining;
// Here we call one constructor from
//another constructor
public class A {
A(int x, int y){
System.out.println(x);
System.out.println(y);
}
A(int x){
this(1000,2000);
A(){
this(100);
public static void main(String[] args) {
A a1=new A();
Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can
also create your own methods to perform certain actions:
Example
public class Main {
static void myMethod() {
// code to be executed
Example Explained
• myMethod() is the name of the method
• static means that the method belongs to the Main class and not an object of the Main class.
You will learn more about objects and how to access methods through objects later in this
tutorial.
• void means that this method does not have a return value. You will learn more about return
values later in this chapter
• Call a Method
• To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
• In the following example, myMethod() is used to print a text (the action),
when it is called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
public static void main(String[] args) {
myMethod();
// Outputs "I just got executed!"
Java Modifiers / Access specifiers
Modifiers
Access Specifier / Access Modifiers
1. private
2. default
3. protected
4. public
private default protected public
Same class yes Yes yes yes
Same package
subclass NO Yes yes yes
Same package
non subclass NO Yes yes yes
different
package No No yes yes
subclass
different
package non No No No yes
subclass
Private:
a. private members are the class are accessible in the same class
Example 1:
package p1;
public class A {
private int i = 10;
private void test(){
System.out.println("From test");
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
10
From test
Example 2:
private members cannot be accesses in same package sub class
package p1;
public class A {
private int i = 10;
private void test(){
System.out.println("From test");
package p1;
public class B extends A{
public static void main(String[] args) {
B b1 = new B();
System.out.println(b1.i);
b1.test();
Output:
error
Note: private members cannot be accessed in different non subclass same
package
Example 3:
package p1;
public class A {
private int i = 10;
private void test(){
System.out.println("From test");
package p1;
public class B {
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
error
Note: private members cannot be accessed in different package sub class
Example 4:
package p1;
public class A {
private int i = 10;
private void test(){
System.out.println("From test");
package p2;
import p1.A;
public class C extends A{
public static void main(String[] args) {
C c1 = new C();
System.out.println(c1.i);
c1.test();
Output:
Error
Note: private members cannot be accessed in different package non sub class
Example 5:
package p1;
public class A {
private int i = 10;
private void test(){
System.out.println("From test");
package p2;
import p1.A;
public class C {
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.i);
a1.test();
}
}
Output:
Error
Important Note:
Private members are accessible only in same class, outside that class
private members cannot be used
default access specifier:
These members are accessible only in same package, outside the package tese
members cannot be accessed
Example 1:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
10
From Test
Example 2:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
package p1;
public class B extends A{
public static void main(String[] args) {
B b1 = new B();
System.out.println(b1.i);
b1.test();
Output:
10
From Test
Example 3:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
package p1;
public class B {
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
10
From Test
Example 4:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
Example 5:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
package p2;
import p1.A;
public class C {
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Protected Access Specifier:
protected members can be accessed in same package and in different package
onlythrough inheritance
Example 1:
package p1;
public class A {
protected int i = 10;
protected void test(){
System.out.println("From Test");
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
10
From Test
Example 2:
package p1;
public class A {
protected int i = 10;
protected void test(){
System.out.println("From Test");
package p1;
public class B extends A{
public static void main(String[] args) {
B b1 = new B();
System.out.println(b1.i);
b1.test();
Example 3:
package p1;
public class A {
protected int i = 10;
protected void test(){
System.out.println("From Test");
package p1;
public class B {
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Example 4:
package p1;
public class A {
protected int i = 10;
protected void test(){
System.out.println("From Test");
package p2;
import p1.A;
public class C extends A{
public static void main(String[] args) {
C c1 = new C();
System.out.println(c1.i);
c1.test();
Output:
10
From Test
Example 5:
package p1;
public class A {
protected int i = 10;
protected void test(){
System.out.println("From Test");
package p2;
import p1.A;
public class C{
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
Error
Public access specifier:
Public access specifier can be accessed anywhere in the project
Note: A class in java can be public or default. It cannot be private or
protected
Example 1:
In the below example we get an error because default class cannot be
accessed in different package
package p1;
class A {
}
package p2;
import p1.A;
public class B extends A{
Output: Error
Note:
1. If a constructor is made public then its object can be created anywhere
in the project
2. If a constructor is made default then its object cannot be created in
different package
3. If a constructor is made private then its object can be created in same
class
4. If a constructor is made protected then its object can be created in
same package only just like default constructor