KEMBAR78
Chapter 4-Classes and Objects | PDF | Programming | Constructor (Object Oriented Programming)
0% found this document useful (0 votes)
25 views72 pages

Chapter 4-Classes and Objects

The document provides an overview of Java programming fundamentals, focusing on classes and objects, including their definitions, structures, and the importance of constructors. It explains how to create classes, instantiate objects, and utilize methods to manipulate data within those objects. Additionally, it covers concepts such as encapsulation, inheritance, polymorphism, and the use of accessors and constructors in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views72 pages

Chapter 4-Classes and Objects

The document provides an overview of Java programming fundamentals, focusing on classes and objects, including their definitions, structures, and the importance of constructors. It explains how to create classes, instantiate objects, and utilize methods to manipulate data within those objects. Additionally, it covers concepts such as encapsulation, inheritance, polymorphism, and the use of accessors and constructors in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 72

Fundamentals Of

Java Programming

Java Programming Language


Classes and Objects
Dr. K. Praveen Kumar
Assistant Professor, CSE Department
Outline
• Classes & Objects

• Class Fundamentals

• Object Fundamentals

• Constructors

• this, static, and final keywords

• Nested and Inner Classes


Class & Object
• A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
• An object is an instance of a certain class.
• After you have created a class, you must create an instance of it
before you can use.
• It is therefore important to understand how the fields and
methods are defined in a class and how they are used to build a
Java program that incorporates the basic OO concepts such as
encapsulation, inheritance, and polymorphism.
• The benefit of Classes: Reusability
Contd.
• Underlying structure of each JAVA programs is CLASSES.

CREATE
CLASS
NES DATA ITEMS
F I basic program
DE OBJECTS
Components
METHODS
General Form of a Class
A class is declared by use of the class keyword.

When you define a class, you declare its exact form and nature.
You do this by specifying the data that it contains ( Form )
and the code that operates on that data ( nature ).

The data , or variables, defined with in a class are called instance


variable because each instance of the class ( Object ) contains its
own copy of these variables. Thus data of one object is separate
and unique from the data for another.

A class declaration only creates a template ; it doesn’t create


actual object.
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
•Methods
•Constructors
•Blocks
•Nested class and interface
Contd.
SYNTAX EXAMPLE

class classname class Circle


{ {
Instance variables are declared INSATANCE VARIABLE
variables declarations;
Declaring variables double PI;
int x,y;
double radius;

methods definitions; Defining methods void printDetails( )


} {

}
}
Contd.
• The basic syntax for a class definition:
class ClassName [extends SuperClassName]
{
[fields declaration] // instance variables
type instance_var1;
type instance_var2;

[methods declaration] // instance methods


type methodname1(parameter-list) {
---------------
---------------------
}
}
Adding Fields: Class Circle with
variables
• Add fields
public class Circle
{
public static final double PI = 3.14159;
private int x, y;
private double radius;
}

• The fields (data) are also called the instance variables.


• The fields defined using static keyword are called static
variables, they are not instance variables.
Introducing Methods
 Classes usually consist of two things:- Instance variable and Methods.
 A method is a collection of statements that are grouped together to
perform an operation

int max(int num1, int


num2)
{
if (num1 > num2) {
return num1;
} else {
return num2;
}
}
Adding Methods to a class
• A class with only data fields has no life. Objects created by such
a class cannot respond to any messages.
• Methods are declared inside the body of the class but
immediately after the declaration of data fields.
• It’s a general rule, It is the methods that determine how a class’
data can be used.
• The general form of a method declaration is:

type MethodName (parameter-list)


{
Method-body;
}
Adding Methods to a class
public class Circle
{
//Instance variables
private final double PI = 3.14159;
private final int x, y; // Center of a Circle
private double radius; // Radius of a Circle
//Methods to return circumference and area
public double getArea()
{
return PI * radius * radius;
} Method Body
public double getCircumference()
{
return 2 * PI * radius;
}
}
What Are Objects?
• Objects are basic read-world/runtime entities or abstract concepts.
• dog, bicycle, car
• Real-world objects have states and behaviors
• Dogs' states: name, color, breed
• Dogs' behaviors: barking, running
• Objects have:
• State → a set of attributes (aka member variables, properties,
data fields) = properties or variables that relate to / describe the
object, with their current values.
• Behavior → a set of operations (aka methods) = actions or
functions that the object can perform to modify itself – its state,
or perform for some external effect / result.
• How do Software objects implement real-world objects?
• Use variables to implement states
• Use methods to implement behaviors
Declaring Objects
• When you create a class, You are creating a new data
type – Abstract Data Type .Use this type to declare a
variable of the class type.
• Obtaining an objects of a class is a two step process:
• 1. Declaration
• Below Declaration will just declare a variable of class type. The
variable doesn’t define the object.
• Declared Variable is able to store the reference to an object of
Circle Type.
• As we have not created any object of class Circle and we haven’t
bCircle
Circle aCircle; aCircle
assigned any reference to aCircle1 , it will be initialized with null.

Circle bCircle;
null
null
Creating objects of a class
• 2. Allocation and Assigning Object to variable of class Type
• Objects are created dynamically using the new keyword.
• Objects in Java Essentially a block of memory that contains space to
store all the instance variables.
• Creating an Object is also referred to as instantiating an object
• aCircle and bCircle refer to Circle objects

aCircle = new Circle() ; bCircle = new Circle() ;


Assigning Object Reference
Variables
• Object reference variables act differently than you might expect
when an assignment takes place.

Circle aCircle = new Circle();


Circle bCircle = new Circle();
bCircle = aCircle;
Before Assignment After Assignment

aCircle bCircle aCircle bCircle

P Q P Q
Automatic garbage
collection
Q
• The object does not have a reference and cannot be
used in future.

• The object becomes a candidate for automatic garbage


collection.

• Java automatically collects garbage periodically and releases


the memory used to be used in the future.
Accessing Object/Circle Data members
• Similar to C syntax for accessing data defined in a structure.

ObjectName.VariableName;
ObjectName.MethodName(parameter-list)

Circle aCircle = new Circle();

aCircle.x = 2.0 // initialize center and radius


aCircle.y = 2.0
aCircle.r = 1.0
Executing Methods in
Object/Circle
• Using Object Methods:

sent ‘message’ to aCircle

Circle aCircle = new Circle();

double area;
aCircle.r = 1.0;
area = aCircle.area();
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class CircleTest
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
} [C:\java programs] java CircleTest
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Better way of Initialising or Access
Data Members x, y, r
• When there too many items to update/access and also
to develop a readable code, generally it is done by
defining specific method for each purpose.
• To initialise/Update a value:
• aCircle.setX( 10 )
• To access a value:
• aCircle.getX()
• These methods are informally called as Accessors or
Setters/Getters Methods.
Assessors – “Getters/Setters”

public class Circle {


public double x,y,r;

//Methods to return circumference and area


public double getX() { return x;}
public double getY() { return y;}
public double getR() { return r;}
public double setX(double x_in) { x = x_in;}
public double serY(double y_in) { y = y_in;}
public double setR(double r_in) { r = r_in;}

}
How does this code looks ? More
readable ?
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class CircleTest
{ [C:\java programs]%: java CircleTest
public static void main(String args[]) Radius=5.0 Area=78.5
{ Radius=5.0 Circumference
Circle aCircle; // creating reference =31.400000000000002
aCircle = new Circle(); // creating object
aCircle.setX(10);
aCircle.setY(20);
aCircle.setR(5);
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.getR()+" Area="+area);
System.out.println("Radius="+aCircle.getR()+" Circumference ="+circumf);
}
}
Object Initialization
• When objects are created, the initial value of data fields is unknown
unless its users explicitly do so. For example,
• ObjectName.DataField1 = 0; // OR
• ObjectName.SetDataField1(0);
• In many cases, it makes sense if this initialisation can be carried out by
default without the users explicitly initializing them.
• For example, if you create an object of the class called “Counter”, it is natural to
assume that the counter record-keeping field is initialized to zero unless
otherwise specified differently.

class Counter
{
int CounterIndex;

}
Counter counter1 = new Counter();

• What is the value of “counter1.CounterIndex” ?


• In Java, this can be achieved though a mechanism called constructors.
What is a Constructor?
• It can be tedious to initialize all of the variables in a class each
time an instance is created.
• Constructor is a special kind of method that gets invoked
“automatically” at the time of object creation.
• Constructor are special in the sense that they have the same
name as the Class they are part of.
• Constructor is normally used for initializing objects with default
values unless different values are supplied.
• A class can have more than one constructor as long as they have
different signature (i.e., different input arguments syntax).
• Constructor in java is a special type of method that is used to
initialize the object.
General Form of a Constructor
• Java constructor is invoked at the time of object creation. It constructs
the values i.e. provides data for the object that is why it is known as
constructor.
• A Constructor Initializes an object upon creation. It has the same name
as the class in which it resides and is syntactically similar to method.
Access-modifier ClassName(Parameter List)
{

// Constructor body

}
Defining a Constructor
• Like any other method
public class ClassName { public class Circle {

// Data Fields… // Data Fields…

// Constructor // Constructor
public ClassName() public Circle()
{
{ /* Method Body Statements
/* Method Body Statements initialising Data Fields */
initialising Data Fields*/ }
}
//Methods to manipulate data
//Methods to manipulate data fields
fields }
}

• Invoking:
• There is NO explicit invocation statement needed: When the object creation
statement is executed, the constructor method will be executed automatically.
Defining a Constructor: Example
public class Circle {
public static final double PI=3.14;
public int x,y;
public double radius;

// Constructor
public Circle()
{
x = 0;
y = 0;
radius = 4;
}
//Methods to update or access instance variables
public void increaseRadius()
{
x = x + 1;
}
public double getCircumference()
{
return 2*PI*radius;
}
public double getArea()
{
return PI*radius*radius;
}
}
Driver Class and What is the output ?
class CircleTest
{
public static void main(String args[])
{
Circle c1 = new Circle();
c1.increaseRadius();
double circumference = c1.getCircumference();
double area=c1.getArea();
c1.increaseRadius();
System.out.println(“Area is “+c1.getArea());
System.out.println(“Circumference is “+c1.getCircumference()
}
}
Types of Constructors
• Default Constructor
• If you do not define any constructor in your class, java
generates one for you by default. This constructor is
known as default constructor.
• No-Arg Constructor
• Constructor with no arguments is known as no-arg
constructor. The signature is same as default constructor,
however body can have any code unlike default
constructor where the body does nothing.
• Parameterized Constructor
• Constructor with arguments is known as parameterized
constructor.
Parameterized Constructor
• Adding a Multiple-Parameters Constructor to our Circle Class
public class Circle
{
public static final double PI=3.14;
public int x,y;
public double radius;
// Constructor
public Circle(int centreX, int centreY, double r)
{
x = centreX;
y = centreY;
radius = r;
}
//Methods to return circumference and area
public double circumference() { return 2*PI*r; }
public double area() { return PI * r * r; }
}
}
Constructors initialise Objects
• Recall the following OLD Code Segment:

Circle aCircle = new Circle();


aCircle.x = 10.0; // initialize center and radius
aCircle.y = 20.0
aCircle.r = 5.0;
aCircle = new Circle() ;
At creation time the center and radius
are not defined.

These values are explicitly set later.


Constructors initialise Objects
• With defined constructor

Circle aCircle = new Circle(10.0, 20.0, 5.0);

aCircle = new Circle(10, 20, 5.0) ;

aCircle is created with center (10, 20)


and radius 5
Constructor Overloading ( Multiple Constructors
)
• Constructor overloading is a technique in Java in which a class can have
any number of constructors that differ in parameter lists. The compiler
differentiates these constructors by taking into account the number of
parameters in the list and their type.

• Sometimes want to initialize in a number of different ways, depending on


circumstance.

• Constructor overloading is way of having more than one constructor


which does different tasks.

• This can be supported by having multiple constructors having different


input arguments.

• Overloaded constructors are differentiated on the basis of their type of


parameters or number of parameters.
Example.
public class Circle {
public int x,y
double radius; //instance variables
// Constructors
public Circle(double centreX, double centreY, double r)
{
x = centreX; y = centreY; radius = r;
}

public Circle(double r)
{ x=0; y=0; radius = r;
}
public Circle() { x=0; y=0; r=1.0; }

//Methods to return circumference and area


public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
Initializing with constructors
public class TestCircles {

public static void main(String args[]){


Circle aCircle = new Circle( 10, 12, 20.0);
Circle bCircle = new Circle(10.0);

Circle cCircle = new Circle();


}
}

aCircle = new Circle(10, 12, 20)


bCircle = new Circle(10)
cCircle = new Circle()

Centre = (10,12) Centre = (0,0)


Radius = 20 Centre = (0,0) Radius = 1
Radius=10
Rules or properties of a constructor
• Constructor will be called automatically when the object is
created.
• Constructor name must be same as name of the class.
• The access specifier of the constructor may or may not be
private.
• If the access specifier of the constructor is private then an
object of corresponding class can be created in the context of
the same class but not in the context of some other classes.
• If the access specifier of the constructor is not private then
an object of corresponding class can be created both in the
same class context and in other class context.
Difference between constructor and
method in java

Java Constructor Java Method


Constructor is used to initialize Method is used to expose
the state of an object. behaviour of an object.
Constructor must not have Method must have return type.
return type.
Constructor is invoked Method is invoked explicitly.
implicitly.
The java compiler provides a Method is not provided by
default constructor if you don't compiler in any case.
have any constructor.

Constructor name must be Method name may or may not


same as the class name. be same as class name.
Variable Hiding or Shadowing
“this” keyword
• Variable hiding or shadowing occurs when a variable declared
within a certain scope (decision block, method, or inner class)
has the same name as a variable declared in an outer scope
(class definition / instance variable).
This outer variable is said to be shadowed /hidden by the inner
variable.
• How To access hidden or shadowed variable?
• When a global variable is hidden or shadowed by local
variable.
• To access the hidden static variable inside a method or block
– use class name.
• To access the hidden non-static variable – use “this”
keyword. this keyword refers to current instance of the class.
public class FieldShadowingExample{
String name = "Krishna";
int age = 25;
public void display(){
String name = "Vishnu";
int age = 22;
System.out.println("Name: "+name);
System.out.println("age: "+age);
System.out.println("Name: "+this.name);
System.out.println("age: "+this.age);
}
public static void main(String args[]){
new FieldShadowingExample().display();
}
} Name: Vishnu
age: 22
Name: Krishna
age: 25
More Usage of “this” keyword
• this keyword can be used to refer current class instance
variable.
• this() can be used to invoke current class constructor.
• this keyword can be used to invoke current class
method (implicitly)
• this can be passed as an argument in the method call.
• this keyword can also be used to return the current
class instance.
• this keyword can be used to refer current class instance
variable.
//example of this keyword
class Student{
int id;
String name;

Student(int id, String name){


this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
• this() can be used to invoke current class constructor.

class Student{
int id; class A{
String name;
Student()
A(){
{ System.out.println("hello a")
System.out.println("default constructor is invoked"); }
} A(int x){
this();
Student( int id, String name)
{
System.out.println(x);
this();//it is used to invoke current class constructor. }
this.id = id; }
this.name = name; class TestThis5{
}
void display(){ System.out.println(id+" "+name); }
public static void main(String
args[]){
public static void main(String args[]) A a=new A(10);
{ }
Student e1 = new Student(111,"karan");
}
Student e2 = new Student(222,"Aryan"); hello a
e1.display(); 10
e2.display();
}
• this keyword can be used to invoke current class method (implicitly)
//example of this keyword
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m(); //compiler does it for you.
}
void p(){
n();
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
• this keyword can be passed as an argument in the method.
//example of this keyword
class Student {
void m(Student obj) {
System.out.println("method is invoked");
}
void p(){
m(this);
}

public static void main(String args[]){


Student s1 = new Student();
s1.p();
}
}
• The this keyword can be used to return current class
instance. //example of this keyword
class A
{
int a,b;
A getA()
{
a=10;
b=20;
return this;
}
void msg()
{System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
A ob1=new A();
A ob2=ob1.getA();
}
}
Method Overloading
• What is Method Overloading?
• Method Overloading is a feature that allows a class to have
two or more methods having same name, if their
parameter lists are different.
• Why use Method Overloading in Java ?
• If we have to perform only one common operation with
difference in arguments, having same name of the methods
increases the readability of the program.
• Different ways to overload the method
• By changing number of parameters list
• By changing the data type of parameters list
• Order of parameters list
Contd.
• Method Overloading by changing the no. of parameters
class Calculation{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Contd.
• Method Overloading by changing data type of parameter lists
class Calculation2
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);

}
}
Contd.
• Method Overloading by changing order of parameter lists
class Calculation2
{
void sum(int a, float b)
{
System.out.println(a+b);
}
void sum(float a, int b)
{
System.out.println(a+b);
}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10,10.5);
obj.sum(10.5,10);

}
}
• Valid/invalid cases of method overloading
• Case 1:
• int mymethod(int a, int b, float c)
• int mymethod(int var1, int var2, float var3)
• Case 2:
• int mymethod(int a, int b)
• int mymethod(float var1, float var2)
• Case 3:
• int mymethod(int a, int b)
• int mymethod(int num)
• Case 4:
• int mymethod(int a, int b)
• float mymethod(int var1, int var2)
• Case 5:
• float mymethod(int a, float b)
• float mymethod(float var1, int var2)
Java Static Keyword
• The static keyword in java is used for memory management mainly.
We can apply java static keyword with variables, methods, blocks and
nested class.
• Advantage of static variable
It makes your program memory efficient (i.e it saves
memory).
The static can be:
• variable (also known as class variable)
• method (also known as class method)
• block
• nested class
Static Variables
• Define using static:
public class Circle {
// class variable, one for the Circle class, how many circles
public static int numCircles;

//instance variables,one for each instance of a Circle


public double x,y,r;
// Constructors...
}

• Access with the class name (ClassName.StatVarName):

nCircles = Circle.numCircles;
Static Variables - Example
• Using static variables:

public class Circle {


// class variable, one for the Circle class, how many circles
private static int numCircles = 0;
private double x,y,r;

// Constructors...
Circle (double x, double y, double r){
this.x = x;
this.y = y;
this.r = r;
numCircles++;
}
}
Class Variables - Example
• Using static variables:
public class CountCircles {

public static void main(String args[]){


Circle circleA = new Circle( 10, 12, 20); //
numCircles = 1
Circle circleB = new Circle( 5, 3, 10); //
numCircles = 2
}
}circleA = new Circle(10, 12, 20) circleB = new Circle(5, 3, 10)

numCircles
Instance Vs Static Variables
• Instance variables : One copy per object. Every
object has its own instance variable.
• E.g. x, y, r (centre and radius in the circle)

• Static variables : One copy per class.


• E.g. numCircles (total number of circle objects created)
Static Methods
• A class can have methods that are defined as static
(e.g., main method).
• They are prefixed with keyword “static”
• Static methods are generally used to group related
library functions that don’t depend on data members
of its class.
• A static method in Java is a method that is part of a
class rather than an instance of that class.
• Static methods have access to class variables (static
variables) without using the class's object (instance).
• Only static data may be accessed by a static method.
Static Methods
// //method to display values
Java Program to demonstrate the use void display()
of a static method. {System.out.println(rollno+" "+name+" "+coll
class Student{ ege);}
int rollno; }
String name; //
static String college = “PVPSIT"; Test class to create and display the values of o
bject
//
static method to change the value of public class TestStaticMethod{
static variable public static void main(String args[]){
static void change(){ Student.change();//calling change method
college = “VRSEC"; //creating objects
Student s1 = new Student(111,"Karan");
}
Student s2 = new Student(222,"Aryan");
//
constructor to initialize the variable
Student s3 = new Student(333,"Sonoo");
//calling display method
Student(int r, String n){
s1.display();
rollno = r; s2.display();
name = n; s3.display();
} }
Static and Non-static
• We can access static variables without creating an instance of
the class
• As they are already available at class loading time, we can use
them in any of our methods.
• We cannot use non static methods and variables without
creating an instance of the class as they are bound to the
instance of the class.
• They are initialized by the constructor when we create the
object using new operator.
How it worksBasic Steps of how objects are created
1. Class is loaded by JVM
2. Static variable and methods are loaded and initialized
and available for use
3. Constructor is called to instantiate the non static
variables
4. Non static variables and methods are now available

• As all the non static variable are


available only after the constructor
is called
Nested Classes and Inner Classes
• What is Nested Class?
• The Java programming language allows us to define a class
within another class. Such a class is called a nested class. A
nested class is a member of its enclosing class.
• Syntax?
class OuterClassName
{
...
class NestedClassName Outer Class
{
...
Nested
} Class
}
Types of Nested
• Nested classes are divided into two types:
Classes
– Static Nested classes
– Non-static Nested classes
• Nested classes that are declared static are simply called
static nested classes.
Why Use Nested Classes?

• Logical grouping of classes—If a class is useful to only one other


class, then it is logical to embed it in that class and keep the two
together.

• Increased encapsulation—Consider two top-level classes, A and B,


where B needs access to members of A that would otherwise be
declared private. By hiding class B within class A, A's members
can be declared private and B can access them. In addition, B itself
can be hidden from the outside world.

• More readable, maintainable code—Nesting small classes within


top-level classes places the code closer to where it is used.
Non Static Nested Class
( Inner Class )
• Non-static Nested class is most important type of nested class. It is
also known as Inner class.

• It has access to all variables and methods of Outer class and may
refer to them directly. But the reverse is not true, that is, Outer class
cannot directly access members of Inner class.

• An inner class is associated with an instance of its enclosing class


and has direct access to that object's methods and data members.

• Objects that are instances of an inner class exist within an instance


of the outer class.
Contd.
• Consider the following classes:
class OuterClass
{
...
class InnerClass
{
...
}
}
Contd.
• An instance of InnerClass can exist only within an instance of
OuterClass and has direct access to the methods and fields of its
enclosing instance.
class Outer }
{ class Test
public void display() {
{ public static void main(String[] args)
Inner in=new Inner(); {
in.show(); Outer ot=new Outer();
} ot.display();
}
class Inner }
{
public void show()
{
display();
System.out.println("Inside inner");
}
}
Contd.

• To instantiate an inner class, we must first instantiate the outer class.


Then, create the inner object within the outer object.
• Syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Example for Inner class
class Outer class Test
{ {
int count; public static void main(String[] args)
public void display() {
{ Outer ot=new Outer();
Inner in=new Inner(); Outer.Inner in= ot.new Inner();
in.show(); in.show();
} }
}
class Inner
{
public void show()
{
display();
System.out.println("Inside inner "+(++count));
}
}
}
Static Nested Classes
• Nested classes that are declared static are called static nested classes.
• A static nested class is associated with its outer class to access static
/class methods and static /class variables.

• A static nested class cannot refer directly to instance variables or


methods defined in its enclosing class.

• It can use them only through an object reference.

• Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass

• For example, to create an object for the static nested class, use this
syntax:
OuterClass.StaticNestedClass nestedObject =
new
OuterClass.StaticNestedClass();
Example
class TestOuter
{
static int data=30; Nested static class doesn’t need
a reference of Outer class but a
static class Inner nonstatic nested class or Inner
{
void msg() class requires Outer class
{ reference.
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestOuter.Inner obj=new TestOuter.Inner();
obj.msg();
}
Note:

•When we compile a nested class, two different class files will be created
with names

• Outerclass.class
Outerclass$Nestedclass.class

You might also like