SlideShare a Scribd company logo
Programming in Java
Lecture 5: Objects and Classes
By
Ravi Kant Sahu
Asst. Professor, LPU
Contents
• Class
• Object
• Defining and adding variables
• Nested Classes
• Abstract Class
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
OBJECTS AND CLASS
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
4
Class
• A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
Circle
centre
radius
circumference()
area()
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
What is a class?
• A class can be defined as a template/ blue print that
describe the behaviors/states that object of its type
support.
• A class is the blueprint from which individual objects
are created.
• A class defines a new data type which can be used to
create objects of that type. Thus, a class is a template
for an object, and an object is an instance of a class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Classes and Objects
• A Java program consists of one or more classes.
• A class is an abstract description of objects.
• Here is an example class:
class Dog { ...description of a dog goes here... }
• Here are some objects of that class:
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
7
More Objects
• Here is another example of a class:
– class Window { ... }
• Here are some examples of Windows:
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• The data, or variables, defined within a class are called
instance variables because each instance of the class (that
is, each object of the class) contains its own copy of these
variables.
• The code is contained within methods.
• The methods and variables defined within a class are
called members of the class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Defining Classes
 The basic syntax for a class definition:
 Bare bone class – no fields, no methods
public class Circle {
// my circle class
}
class ClassName
{
[fields declaration]
[methods declaration]
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Adding Fields: Class Circle with fields
• Add fields
• The fields (data) are also called the instance
variables.
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Circle Class
• aCircle, bCircle simply refers to a Circle object, It is
not an object itself.
aCircle
Points to nothing (Null Reference)
bCircle
Points to nothing (Null Reference)
null null
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Creating objects of a class
• An object is an instance of the class which has well-
defined attributes and behaviors.
• Objects are created dynamically using the new keyword.
• aCircle and bCircle refer to Circle objects.
bCircle = new Circle();aCircle = new Circle();
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P
aCircle
Q
bCircle
Before Assignment
P
aCircle
Q
bCircle
Before Assignment
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Adding Methods
• 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.
• The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Adding Methods to Class Circle
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Method Body
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Automatic garbage collection
• 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.
Q
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
finalize()
• The finalize() method is declared in the java.lang.Object class.
• Before an object is garbage collected, the runtime system calls
its finalize() method.
• The intent is for finalize() to release system resources such as
open files or open sockets before getting collected.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Accessing Object/Circle Data
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Executing Methods in Object/Circle
• Using Object Methods:
Circle aCircle = new Circle();
double area;
aCircle.r = 1.0;
area = aCircle.area();
sent ‘message’ to aCircle
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Nested Class
• The Java programming language allows us to define a
class within another class. Such a class is called a nested
class.
Example:
class OuterClass
{
...
class NestedClass
{
...
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Types of Nested Classes
• A nested class is a member of its enclosing class.
• Nested classes are divided into two categories:
– static
– non-static
• Nested classes that are declared static are simply
called static nested classes.
• Non-static nested classes are called inner classes.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Static Nested Classes
• A static nested class is associated with its outer class similar to class
methods and 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();
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Inner Classes
• An inner class is associated with an instance of its enclosing class
and has direct access to that object's methods and fields.
• Because an inner class is associated with an instance, it cannot
define any static members itself.
• Objects that are instances of an inner class exist within an instance
of the outer class.
• Consider the following classes:
class OuterClass {
...
class InnerClass { ... }
}
• 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.
• 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();
• Additionally, there are two special kinds of inner classes:
– local classes and
– anonymous classes (also called anonymous inner classes).
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Local Classes
• Local classes are classes that are defined in a block, which is a
group of zero or more statements between balanced braces.
• For example, we can define a local class in a method body, a for
loop, or an if clause.
• A local class has access to the members of its enclosing class.
• A local class has access to local variables. However, a local class
can only access local variables that are declared final.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Anonymous Classes
• Anonymous classes enable us to declare and instantiate a class
at the same time.
• They are like local classes except that they do not have a
name.
• The anonymous class expression consists of the following:
1. The new operator
2. The name of an interface to implement or a class to extend.
3. Parentheses that contain the arguments to a constructor, just like a
normal class instance creation expression.
4. A body, which is a class declaration body. More specifically, in
the body, method declarations are allowed but statements are not.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
 Anonymous classes have the same access to local variables of the enclosing
scope as local classes:
• An anonymous class has access to the members of its enclosing class.
• An anonymous class cannot access local variables in its enclosing scope that are not
declared as final.
 Anonymous classes also have the same restrictions as local classes with
respect to their members:
• We cannot declare static initializers or member interfaces in an anonymous class.
• An anonymous class can have static members provided that they are constant
variables.
 Note that we can declare the following in anonymous classes:
• Fields
• Extra methods (even if they do not implement any methods of the supertype)
• Local classes
• we cannot declare constructors in an anonymous class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Note:
When we compile a nested class, two different class files will
be created with names
Outerclass.class
Outerclass$Nestedclass.class
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Questions

More Related Content

PPTX
Introduction about Python by JanBask Training
JanBask Training
 
PPTX
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
PPT
Generics in java
suraj pandey
 
PPTX
Java Queue.pptx
vishal choudhary
 
PPTX
Super keyword in java
Hitesh Kumar
 
PPTX
Chapter 07 inheritance
Praveen M Jigajinni
 
PDF
Basic i/o & file handling in java
JayasankarPR2
 
PPTX
Templates in C++
Tech_MX
 
Introduction about Python by JanBask Training
JanBask Training
 
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Generics in java
suraj pandey
 
Java Queue.pptx
vishal choudhary
 
Super keyword in java
Hitesh Kumar
 
Chapter 07 inheritance
Praveen M Jigajinni
 
Basic i/o & file handling in java
JayasankarPR2
 
Templates in C++
Tech_MX
 

What's hot (20)

PPTX
20.3 Java encapsulation
Intro C# Book
 
PPTX
this keyword in Java.pptx
ParvizMirzayev2
 
PPTX
6. static keyword
Indu Sharma Bhardwaj
 
PDF
Design Pattern qua ví dụ thực tế
VKhang Yang
 
PPTX
Member Function in C++
NikitaKaur10
 
PPTX
Inheritance In Java
Manish Sahu
 
PDF
Classes and objects
Nilesh Dalvi
 
PPTX
Inheritance In Java
Darpan Chelani
 
PDF
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
PPTX
Basic Graphics in Java
Prakash Kumar
 
PPTX
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
PPTX
Class template
Kousalya M
 
PDF
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
PPTX
Templates in c++
ThamizhselviKrishnam
 
PPT
Operator Overloading
Nilesh Dalvi
 
PPTX
Polymorphism presentation in java
Ahsan Raja
 
PPTX
Friend function & friend class
Abhishek Wadhwa
 
PDF
Methods in Java
Jussi Pohjolainen
 
PPTX
Inner classes in java
PhD Research Scholar
 
20.3 Java encapsulation
Intro C# Book
 
this keyword in Java.pptx
ParvizMirzayev2
 
6. static keyword
Indu Sharma Bhardwaj
 
Design Pattern qua ví dụ thực tế
VKhang Yang
 
Member Function in C++
NikitaKaur10
 
Inheritance In Java
Manish Sahu
 
Classes and objects
Nilesh Dalvi
 
Inheritance In Java
Darpan Chelani
 
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Basic Graphics in Java
Prakash Kumar
 
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
Class template
Kousalya M
 
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Templates in c++
ThamizhselviKrishnam
 
Operator Overloading
Nilesh Dalvi
 
Polymorphism presentation in java
Ahsan Raja
 
Friend function & friend class
Abhishek Wadhwa
 
Methods in Java
Jussi Pohjolainen
 
Inner classes in java
PhD Research Scholar
 
Ad

Viewers also liked (18)

PPTX
Java- Nested Classes
Prabhdeep Singh
 
DOCX
Nested classes in java
Richa Singh
 
PPTX
Questions for Class I & II
Saloni Jaiswal
 
PDF
Jun 2012(1)
Arjun Shanka
 
PDF
Networking
Ravi Kant Sahu
 
PDF
Sms several papers
Arjun Shanka
 
PDF
Swing api
Ravi_Kant_Sahu
 
PDF
Internationalization
Ravi Kant Sahu
 
PDF
Basic IO
Ravi_Kant_Sahu
 
PDF
Distributed Programming (RMI)
Ravi Kant Sahu
 
PDF
Multi threading
Ravi Kant Sahu
 
PDF
Servlets
Ravi Kant Sahu
 
PDF
Packages
Ravi Kant Sahu
 
PDF
Event handling
Ravi Kant Sahu
 
PDF
List classes
Ravi_Kant_Sahu
 
PDF
Collection framework
Ravi_Kant_Sahu
 
PDF
Generics
Ravi_Kant_Sahu
 
Java- Nested Classes
Prabhdeep Singh
 
Nested classes in java
Richa Singh
 
Questions for Class I & II
Saloni Jaiswal
 
Jun 2012(1)
Arjun Shanka
 
Networking
Ravi Kant Sahu
 
Sms several papers
Arjun Shanka
 
Swing api
Ravi_Kant_Sahu
 
Internationalization
Ravi Kant Sahu
 
Basic IO
Ravi_Kant_Sahu
 
Distributed Programming (RMI)
Ravi Kant Sahu
 
Multi threading
Ravi Kant Sahu
 
Servlets
Ravi Kant Sahu
 
Packages
Ravi Kant Sahu
 
Event handling
Ravi Kant Sahu
 
List classes
Ravi_Kant_Sahu
 
Collection framework
Ravi_Kant_Sahu
 
Generics
Ravi_Kant_Sahu
 
Ad

Similar to Classes and Nested Classes in Java (20)

PDF
Methods and constructors
Ravi_Kant_Sahu
 
PDF
Java keywords
Ravi_Kant_Sahu
 
PDF
Keywords and classes
Ravi_Kant_Sahu
 
PDF
Inheritance
Ravi_Kant_Sahu
 
PPT
4. Classes and Methods
Nilesh Dalvi
 
PPT
L5 classes, objects, nested and inner class
teach4uin
 
PDF
Classes and Object Concept Object Oriented Programming in Java
gedeios
 
PDF
Java defining classes
Mehdi Ali Soltani
 
PPTX
Abstraction in java [abstract classes and Interfaces
Ahmed Nobi
 
PPTX
Module 4_Ch2 - Introduction to Object Oriented Programming.pptx
jhesorleylaid2
 
PPTX
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
PPTX
Object Oriented Programming_Lecture 2
Mahmoud Alfarra
 
PPTX
object oriented programming unit two ppt
isiagnel2
 
PDF
ITFT-Classes and object in java
Atul Sehdev
 
PPTX
PPT Lecture-1.4.pptx
HimanshuPandey957216
 
PPT
Lecture 2 classes i
the_wumberlog
 
PPTX
Inheritance in Java is a mechanism in which one object acquires all the prope...
Kavitha S
 
PPTX
Java chapter 5
Abdii Rashid
 
PPT
A1771937735_21789_14_2018__16_ Nested Classes.ppt
RithwikRanjan
 
PPTX
L22 multi-threading-introduction
teach4uin
 
Methods and constructors
Ravi_Kant_Sahu
 
Java keywords
Ravi_Kant_Sahu
 
Keywords and classes
Ravi_Kant_Sahu
 
Inheritance
Ravi_Kant_Sahu
 
4. Classes and Methods
Nilesh Dalvi
 
L5 classes, objects, nested and inner class
teach4uin
 
Classes and Object Concept Object Oriented Programming in Java
gedeios
 
Java defining classes
Mehdi Ali Soltani
 
Abstraction in java [abstract classes and Interfaces
Ahmed Nobi
 
Module 4_Ch2 - Introduction to Object Oriented Programming.pptx
jhesorleylaid2
 
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
Object Oriented Programming_Lecture 2
Mahmoud Alfarra
 
object oriented programming unit two ppt
isiagnel2
 
ITFT-Classes and object in java
Atul Sehdev
 
PPT Lecture-1.4.pptx
HimanshuPandey957216
 
Lecture 2 classes i
the_wumberlog
 
Inheritance in Java is a mechanism in which one object acquires all the prope...
Kavitha S
 
Java chapter 5
Abdii Rashid
 
A1771937735_21789_14_2018__16_ Nested Classes.ppt
RithwikRanjan
 
L22 multi-threading-introduction
teach4uin
 

More from Ravi_Kant_Sahu (12)

PDF
Common Programming Errors by Beginners in Java
Ravi_Kant_Sahu
 
PDF
Gui programming (awt)
Ravi_Kant_Sahu
 
PDF
Event handling
Ravi_Kant_Sahu
 
PDF
String handling(string buffer class)
Ravi_Kant_Sahu
 
PDF
String handling(string class)
Ravi_Kant_Sahu
 
PDF
Packages
Ravi_Kant_Sahu
 
PDF
Array
Ravi_Kant_Sahu
 
PDF
Wrapper classes
Ravi_Kant_Sahu
 
PDF
Operators in java
Ravi_Kant_Sahu
 
PDF
Control structures in Java
Ravi_Kant_Sahu
 
PDF
Genesis and Overview of Java
Ravi_Kant_Sahu
 
PDF
L2 datatypes and variables
Ravi_Kant_Sahu
 
Common Programming Errors by Beginners in Java
Ravi_Kant_Sahu
 
Gui programming (awt)
Ravi_Kant_Sahu
 
Event handling
Ravi_Kant_Sahu
 
String handling(string buffer class)
Ravi_Kant_Sahu
 
String handling(string class)
Ravi_Kant_Sahu
 
Packages
Ravi_Kant_Sahu
 
Wrapper classes
Ravi_Kant_Sahu
 
Operators in java
Ravi_Kant_Sahu
 
Control structures in Java
Ravi_Kant_Sahu
 
Genesis and Overview of Java
Ravi_Kant_Sahu
 
L2 datatypes and variables
Ravi_Kant_Sahu
 

Recently uploaded (20)

PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 

Classes and Nested Classes in Java

  • 1. Programming in Java Lecture 5: Objects and Classes By Ravi Kant Sahu Asst. Professor, LPU
  • 2. Contents • Class • Object • Defining and adding variables • Nested Classes • Abstract Class Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 3. OBJECTS AND CLASS Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. 4 Class • A class is a collection of fields (data) and methods (procedure or function) that operate on that data. Circle centre radius circumference() area() Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. What is a class? • A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support. • A class is the blueprint from which individual objects are created. • A class defines a new data type which can be used to create objects of that type. Thus, a class is a template for an object, and an object is an instance of a class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Classes and Objects • A Java program consists of one or more classes. • A class is an abstract description of objects. • Here is an example class: class Dog { ...description of a dog goes here... } • Here are some objects of that class: Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. 7 More Objects • Here is another example of a class: – class Window { ... } • Here are some examples of Windows: Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. • The data, or variables, defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. • The code is contained within methods. • The methods and variables defined within a class are called members of the class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. Defining Classes  The basic syntax for a class definition:  Bare bone class – no fields, no methods public class Circle { // my circle class } class ClassName { [fields declaration] [methods declaration] } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. Adding Fields: Class Circle with fields • Add fields • The fields (data) are also called the instance variables. public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. Circle Class • aCircle, bCircle simply refers to a Circle object, It is not an object itself. aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. Creating objects of a class • An object is an instance of the class which has well- defined attributes and behaviors. • Objects are created dynamically using the new keyword. • aCircle and bCircle refer to Circle objects. bCircle = new Circle();aCircle = new Circle(); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; P aCircle Q bCircle Before Assignment P aCircle Q bCircle Before Assignment Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15. Adding Methods • 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. • The general form of a method declaration is: type MethodName (parameter-list) { Method-body; } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. Adding Methods to Class Circle public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } } Method Body Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. Automatic garbage collection • 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. Q Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. finalize() • The finalize() method is declared in the java.lang.Object class. • Before an object is garbage collected, the runtime system calls its finalize() method. • The intent is for finalize() to release system resources such as open files or open sockets before getting collected. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. Accessing Object/Circle Data Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 ObjectName.VariableName ObjectName.MethodName(parameter-list) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. Executing Methods in Object/Circle • Using Object Methods: Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area(); sent ‘message’ to aCircle Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21. Nested Class • The Java programming language allows us to define a class within another class. Such a class is called a nested class. Example: class OuterClass { ... class NestedClass { ... } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. Types of Nested Classes • A nested class is a member of its enclosing class. • Nested classes are divided into two categories: – static – non-static • Nested classes that are declared static are simply called static nested classes. • Non-static nested classes are called inner classes. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 23. 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. Static Nested Classes • A static nested class is associated with its outer class similar to class methods and 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(); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 25. Inner Classes • An inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. • Because an inner class is associated with an instance, it cannot define any static members itself. • Objects that are instances of an inner class exist within an instance of the outer class. • Consider the following classes: class OuterClass { ... class InnerClass { ... } }
  • 26. • 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. • 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(); • Additionally, there are two special kinds of inner classes: – local classes and – anonymous classes (also called anonymous inner classes). Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 27. Local Classes • Local classes are classes that are defined in a block, which is a group of zero or more statements between balanced braces. • For example, we can define a local class in a method body, a for loop, or an if clause. • A local class has access to the members of its enclosing class. • A local class has access to local variables. However, a local class can only access local variables that are declared final. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 28. Anonymous Classes • Anonymous classes enable us to declare and instantiate a class at the same time. • They are like local classes except that they do not have a name. • The anonymous class expression consists of the following: 1. The new operator 2. The name of an interface to implement or a class to extend. 3. Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. 4. A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 29.  Anonymous classes have the same access to local variables of the enclosing scope as local classes: • An anonymous class has access to the members of its enclosing class. • An anonymous class cannot access local variables in its enclosing scope that are not declared as final.  Anonymous classes also have the same restrictions as local classes with respect to their members: • We cannot declare static initializers or member interfaces in an anonymous class. • An anonymous class can have static members provided that they are constant variables.  Note that we can declare the following in anonymous classes: • Fields • Extra methods (even if they do not implement any methods of the supertype) • Local classes • we cannot declare constructors in an anonymous class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 30. Note: When we compile a nested class, two different class files will be created with names Outerclass.class Outerclass$Nestedclass.class Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)