SlideShare a Scribd company logo
• Any entity that has state and behavior is known as an object.
• Object is a basic unit of Object Oriented Programming.
• Object represents the real life entities.
• It can be physical or logical.
• An Object can be defined as an instance of a class.
• Java program creates many objects, which interact by invoking methods.
• An object contains an address and takes up some space in memory.
• It communicates without knowing details of each other's data or code.
1
Object
2
Characteristics of Object
• An object consists of:
• State :
• It is represented by attributes of an object.
• It also reflects the properties of an object.
• Behavior :
• It is represented by methods of an object.
• It reflects response of an object with other objects.
• Identity :
• It gives a unique name to an object and enables one
object to interact with other objects.
• Method:
• A method is a collection of statements that perform
some specific task and return result to the caller.
• An object is a real-world entity.
• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.
• Objects correspond to things found in the real world.
• Graphics program may have objects such as “circle”, “square”, “menu”.
• An online shopping system have objects such as “shopping cart”, “customer”, and
“product”.
• Example of an object: dog
3
Object Definition and Example
• Definition:
• Collection of objects is called class.
• A class is a group of objects which have common properties.
• It is defined as template or blueprint from which objects are created.
• It is a logical entity.
• It can't be physical.
• Class doesn't consume any space
• It represents the set of properties or methods that are common to all
objects of one type 4
Class
5
Class
• When an object of a class is created, the class is said to be instantiated.
• All the instances share the attributes and the behavior of the class.
• The values of those attributes, i.e. the state are unique for each object.
• A single class may have any number of instances.
• Example
6
7
• A class in Java can contain:
• Fields/Variables/data members
• Methods
• Constructors
• Nested class
• Constructors are used for initializing new objects.
• Fields are variables that provides the state of the class and its objects.
• Methods are used to implement the behavior of the class and its
objects.
8
Class components
class class_name {
type instance_variable1;
type instance_variable2;
type method_name1(parameter-list)
{
// body of method
}
type method_name2(parameter-list)
{
// body of method
}
} 9
Declaring Classes
class class_name
{
type variable;
type method1();
type method2(parameter-
list);
}
Class_name
variable/attributes;
int number;
float marks;
method()
add();
class structure
class declaration
• Class declarations can include following components
• Modifiers: A class can be public or has default access.
• class keyword: class keyword is used to create a class.
• Class name: The name should begin with an initial letter.
• Body: The class body surrounded by braces, { }.
10
Declaring Classes
• Syntax to create object for a class
class_name object_name=new class_name();
• Create an object for class Student
Student s1=new Student();
Student s2=new Student():
11
Object Creation for a class
12
Class and object Example
class Student {
int id; //field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id);
//accessing member through reference variable
System.out.println(s1.name);
}
}
13
class Student
{
int id;
String name;
}
//Creating another class TestStudent which contains the main method
class TestStudent
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Class and object Example
class Student
{
int id;
String name;
}
class TestStudent
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
14
//Initializing objects
s1.id=101;
s1.name=“Mahesh";
s2.id=102;
s2.name="Amit";
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
Class and object Example
• Classes usually consist of two things:
• Instance variables and
• Methods.
• A method is a way to perform some task.
• The method in Java is a collection of instructions that performs a specific
task.
• A method is
• a block of code or
• collection of statements/ instructions or
• a set of code grouped together to perform a certain task or operation.
15
Method: Definition
• It is used to achieve the reusability of code.
• We write a method once and use it many times.
• We do not require to write code again and again.
• It provides the easy modification and readability of code.
• The method is executed only when we call or invoke it.
• The most important method in Java is the main() method.
16
Method : Uses
• This is the general form of a method declaration:
type name(parameter-list)
{ // body of method
}
17
Method Declaration
18
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;
}
19
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
20
Data Abstraction
• Declare the Circle class, have created a new data type – Data Abstraction
• Can define variables (objects) of that type:
Circle aCircle;
Circle bCircle;
21
Class of Circle cont.
• aCircle, bCircle simply refers to a Circle object, not an object itself.
aCircle
Points to nothing (Null Reference)
bCircle
Points to nothing (Null Reference)
null null
22
Creating objects of a class
• Objects are created dynamically using the new keyword.
• aCircle and bCircle refer to Circle objects
bCircle = new Circle() ;
aCircle = new Circle() ;
23
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
24
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
25
Accessing Data members
• Similar to C syntax for accessing data defined in a
structure.
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)
26
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
27
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
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);
• Return Type:
• Return type is a data type that the method returns.
• If the method does not return anything, then use void keyword.
• Method Name:
• It is a unique name that is used to define the name of a method.
• Parameter List:
• It is the list of parameters separated by a comma.
• It contains the data type and variable name.
• If the method has no parameter, left the parentheses blank.
• Method Body:
• It contains all the actions to be performed enclosed within the curly braces.
28
Method Declaration
• Example
int multi (int a, int b)
{ // method body;
return (a*b);
}
• Example
void add()
{ // method body;
}
29
Method sample example
• There are two types of methods in Java:
• Predefined Method
• User-defined Method
30
Method Types
• Predefined Method
• The method that is already defined in the Java class libraries is known as
predefined methods.
• It is also known as the standard library method or built-in method.
• We can directly use these methods just by calling them in the program at
any point.
• Some pre-defined methods are
• length(), equals(), compareTo(), sqrt(), etc.
• When we call any of the predefined methods in our program, a series of
codes related runs in the background that is already stored in the library.
31
Predefined Method
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
32
Method Types
• The method written by the user or programmer is known as a user-
defined method.
• These methods are modified according to the requirement.
• Example
int EvenOdd(int num)
{ //method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
} 33
User-defined Method
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
} 34
User-defined Method
class Rectangle {
double l;
double b;
// display area of a rectangle
void area()
{
System.out.print(“Area is ");
System.out.println(l * b );
} }
35
Method Example
Program to display area of Rectangle using method.
class BoxDemo {
public static void main(String args[]) {
Rectangle mybox1 = new Rectangle();
Rectangle mybox2 = new Rectangle(); // assign values to mybox1's instance variables
mybox1.l = 10;
mybox1.b = 20;
mybox2.l = 3; /* assign different values to mybox2's instance variables */
mybox2.b = 6;
mybox1.area(); // display volume of first box
mybox2.area(); // display volume of second box
} }
36
Method Example
• If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
• If we have to perform only one operation, having same name of the
methods increases the readability of the program.
• Advantage of method overloading
• Method overloading increases the readability of the program.
• Different ways to overload the method
• There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type
37
Method Overloading
int area(int r)
{
return 3.14 * r * r;
}
int area(int h, int l)
{
return h * l;
}
38
Method Overloading Example
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// Overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
} 39
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25):
" + result);
}
}
Method Overloading Example
• This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
40
Method Overloading Example- Result
• In Java, a constructor is a block of codes similar to the method.
• It is called when an instance of the class is created.
• At the time of calling constructor, memory for the object is allocated in the
memory.
• It is a special type of method which is used to initialize the object.
• Every time an object is created using the new() keyword, at least one
constructor is called.
• It calls a default constructor if there is no constructor available in the class.
• In such case, Java compiler provides a default constructor by default.
41
Constructor
• It is called constructor because it constructs the values at the time of
object creation.
• It is not necessary to write a constructor for a class.
• It is because java compiler creates a default constructor if your class
doesn't have any.
• Rules for creating Java constructor
• There are two rules defined for the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final.
42
Constructor
• There are two types of constructors in Java:
• Default constructor (no-arg constructor)
• Parameterized constructor
• Java Default Constructor
• A constructor is called "Default Constructor" when it doesn't have any
parameter.
• Syntax of default constructor:
<class_name>(){}
• The default constructor is used to provide the default values to the object
like 0, null, etc., depending on the type.
43
Constructor Types
• Java Parameterized Constructor
• A constructor which has a specific number of parameters is called a
parameterized constructor.
• The parameterized constructor is used to provide different values to
distinct objects.
• However, you can provide the same values also.
• Example
Student(int i,String n){
id = i;
name = n;
}
44
Constructor Types
45
class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
class Student {
int id;
String name;
void display() {
System.out.println(id+" "+name);
}
public static void main(String args[]) {
Student s1=new Student();
Student s2=new Student();
//displaying values of the object
s1.display();
s2.display();
}
}
Constructor Example
46
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Parameterized Constructor Example
• Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists.
• They are arranged in a way that each constructor performs a different
task.
• They are differentiated by the compiler by the number of parameters in
the list and their types.
47
Constructor Overloading in Java
48
Constructor Overloading Example
49
• In Java, this is a reference variable
that refers to the current object.
• Usage of Java this keyword
• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from the method.
50
this keyword in Java
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){
System.out.println(rollno+" "+name+" "+fee);
} }
51
Program without this keyword
class TestThis
{
public static void main(String args[])
{
Student s1=new Student(111,“Ankit",5000f);
Student s2=new Student(112,“Sumit",6000f);
s1.display();
s2.display();
}
}
52
0 null 0.0
0 null 0.0
• Parameters (formal arguments/local veriables) and instance
variables are same.
• So, need to use this keyword to distinguish local variable and
instance variable.
Program output
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){
System.out.println(rollno+" "+name+" "+fee);
} }
53
Program with this keyword
class TestThis
{
public static void main(String args[])
{
Student s1=new Student(111,“Ankit",5000f);
Student s2=new Student(112,“Sumit",6000f);
s1.display();
s2.display();
}
}
class Student{
int rollno;
String name;
float fee;
Student(int r, String n, float f){
rollno=r;
name=n;
fee=f;
}
void display(){
System.out.println(rollno+" "+name+" "+fee);
} }
54
Program without this keyword
class TestThis
{
public static void main(String args[])
{
Student s1=new Student(111,“Ankit",5000f);
Student s2=new Student(112,“Sumit",6000f);
s1.display();
s2.display();
}
}
• The static keyword in Java is used for memory management mainly.
• The static keyword belongs to the class than an instance of the class.
• The static can be:
• Variable (also known as a class variable)
• Method (also known as a class method)
• Nested class
• If you declare any variable as static, it is known as a static variable.
55
static keyword in Java
• It makes your program memory efficient (i.e., it saves memory).
• Understanding the problem without static variable
class Student{
int rollno;
String name;
String college=“DYP-ATU";
}
• Suppose there are 500 students in my college.
• Now all instance data members will get memory each time when the object is created.
• "college" refers to the common property of all objects.
• If we make it static, this field will get the memory only once.
56
static keyword in Java
57
class Student{
int rollno; //instance variable
String name;
static String college =“DYP"; //static variable
Student(int r, String n) { //constructor
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}
public class TestStatic
{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//Student.college=“DYP";
s1.display();
s2.display();
}
}
static keyword Example
End of Unit
58

More Related Content

PPTX
UNIT - IIInew.pptx
PPTX
UNIT - IIInew.pptx
PPTX
class as the basis.pptx
PPTX
class as the basis.pptx
PPT
L5 classes, objects, nested and inner class
PPT
L5 classes, objects, nested and inner class
PPTX
C# classes objects
PPTX
C# classes objects
UNIT - IIInew.pptx
UNIT - IIInew.pptx
class as the basis.pptx
class as the basis.pptx
L5 classes, objects, nested and inner class
L5 classes, objects, nested and inner class
C# classes objects
C# classes objects

Similar to Core Java unit no. 1 object and class ppt (20)

PPT
02._Object-Oriented_Programming_Concepts.ppt
PPT
02._Object-Oriented_Programming_Concepts.ppt
PPTX
Pi j2.3 objects
PPTX
Pi j2.3 objects
PPT
Chap01
PPT
Chap01
PPT
Data Hiding and Data Encapsulation of java
PPT
Data Hiding and Data Encapsulation of java
PPTX
Java chapter 4
PPTX
Java chapter 4
PPTX
BCA Class and Object (3).pptx
PPTX
BCA Class and Object (3).pptx
PDF
ITFT-Classes and object in java
PDF
ITFT-Classes and object in java
PPTX
Class introduction in java
PPTX
Class introduction in java
PPT
Java Presentation.ppt
PPT
Java Presentation.ppt
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Pi j2.3 objects
Pi j2.3 objects
Chap01
Chap01
Data Hiding and Data Encapsulation of java
Data Hiding and Data Encapsulation of java
Java chapter 4
Java chapter 4
BCA Class and Object (3).pptx
BCA Class and Object (3).pptx
ITFT-Classes and object in java
ITFT-Classes and object in java
Class introduction in java
Class introduction in java
Java Presentation.ppt
Java Presentation.ppt
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
Ad

Recently uploaded (20)

PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Road Safety tips for School Kids by a k maurya.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPT
Drone Technology Electronics components_1
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Simulation of electric circuit laws using tinkercad.pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
Queuing formulas to evaluate throughputs and servers
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
PPTX
Geodesy 1.pptx...............................................
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPT
Chapter 6 Design in software Engineeing.ppt
PPT
Project quality management in manufacturing
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
bas. eng. economics group 4 presentation 1.pptx
Road Safety tips for School Kids by a k maurya.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
CYBER-CRIMES AND SECURITY A guide to understanding
Drone Technology Electronics components_1
OOP with Java - Java Introduction (Basics)
Simulation of electric circuit laws using tinkercad.pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Queuing formulas to evaluate throughputs and servers
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
Geodesy 1.pptx...............................................
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Chapter 6 Design in software Engineeing.ppt
Project quality management in manufacturing
Ad

Core Java unit no. 1 object and class ppt

  • 1. • Any entity that has state and behavior is known as an object. • Object is a basic unit of Object Oriented Programming. • Object represents the real life entities. • It can be physical or logical. • An Object can be defined as an instance of a class. • Java program creates many objects, which interact by invoking methods. • An object contains an address and takes up some space in memory. • It communicates without knowing details of each other's data or code. 1 Object
  • 2. 2 Characteristics of Object • An object consists of: • State : • It is represented by attributes of an object. • It also reflects the properties of an object. • Behavior : • It is represented by methods of an object. • It reflects response of an object with other objects. • Identity : • It gives a unique name to an object and enables one object to interact with other objects. • Method: • A method is a collection of statements that perform some specific task and return result to the caller.
  • 3. • An object is a real-world entity. • An object is a runtime entity. • The object is an entity which has state and behavior. • The object is an instance of a class. • Objects correspond to things found in the real world. • Graphics program may have objects such as “circle”, “square”, “menu”. • An online shopping system have objects such as “shopping cart”, “customer”, and “product”. • Example of an object: dog 3 Object Definition and Example
  • 4. • Definition: • Collection of objects is called class. • A class is a group of objects which have common properties. • It is defined as template or blueprint from which objects are created. • It is a logical entity. • It can't be physical. • Class doesn't consume any space • It represents the set of properties or methods that are common to all objects of one type 4 Class
  • 5. 5 Class • When an object of a class is created, the class is said to be instantiated. • All the instances share the attributes and the behavior of the class. • The values of those attributes, i.e. the state are unique for each object. • A single class may have any number of instances. • Example
  • 6. 6
  • 7. 7
  • 8. • A class in Java can contain: • Fields/Variables/data members • Methods • Constructors • Nested class • Constructors are used for initializing new objects. • Fields are variables that provides the state of the class and its objects. • Methods are used to implement the behavior of the class and its objects. 8 Class components
  • 9. class class_name { type instance_variable1; type instance_variable2; type method_name1(parameter-list) { // body of method } type method_name2(parameter-list) { // body of method } } 9 Declaring Classes class class_name { type variable; type method1(); type method2(parameter- list); } Class_name variable/attributes; int number; float marks; method() add(); class structure class declaration
  • 10. • Class declarations can include following components • Modifiers: A class can be public or has default access. • class keyword: class keyword is used to create a class. • Class name: The name should begin with an initial letter. • Body: The class body surrounded by braces, { }. 10 Declaring Classes
  • 11. • Syntax to create object for a class class_name object_name=new class_name(); • Create an object for class Student Student s1=new Student(); Student s2=new Student(): 11 Object Creation for a class
  • 12. 12 Class and object Example class Student { int id; //field or data member or instance variable String name; //creating main method inside the Student class public static void main(String args[]) { //Creating an object or instance Student s1=new Student(); //creating an object of Student //Printing values of the object System.out.println(s1.id); //accessing member through reference variable System.out.println(s1.name); } }
  • 13. 13 class Student { int id; String name; } //Creating another class TestStudent which contains the main method class TestStudent { public static void main(String args[]) { Student s1=new Student(); System.out.println(s1.id); System.out.println(s1.name); } } Class and object Example
  • 14. class Student { int id; String name; } class TestStudent { public static void main(String args[]) { Student s1=new Student(); Student s2=new Student(); 14 //Initializing objects s1.id=101; s1.name=“Mahesh"; s2.id=102; s2.name="Amit"; System.out.println(s1.id+" "+s1.name); System.out.println(s2.id+" "+s2.name); } } Class and object Example
  • 15. • Classes usually consist of two things: • Instance variables and • Methods. • A method is a way to perform some task. • The method in Java is a collection of instructions that performs a specific task. • A method is • a block of code or • collection of statements/ instructions or • a set of code grouped together to perform a certain task or operation. 15 Method: Definition
  • 16. • It is used to achieve the reusability of code. • We write a method once and use it many times. • We do not require to write code again and again. • It provides the easy modification and readability of code. • The method is executed only when we call or invoke it. • The most important method in Java is the main() method. 16 Method : Uses
  • 17. • This is the general form of a method declaration: type name(parameter-list) { // body of method } 17 Method Declaration
  • 18. 18 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; }
  • 19. 19 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
  • 20. 20 Data Abstraction • Declare the Circle class, have created a new data type – Data Abstraction • Can define variables (objects) of that type: Circle aCircle; Circle bCircle;
  • 21. 21 Class of Circle cont. • aCircle, bCircle simply refers to a Circle object, not an object itself. aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null
  • 22. 22 Creating objects of a class • Objects are created dynamically using the new keyword. • aCircle and bCircle refer to Circle objects bCircle = new Circle() ; aCircle = new Circle() ;
  • 23. 23 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
  • 24. 24 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
  • 25. 25 Accessing Data members • Similar to C syntax for accessing data defined in a structure. 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)
  • 26. 26 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
  • 27. 27 Using Circle Class // Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { 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);
  • 28. • Return Type: • Return type is a data type that the method returns. • If the method does not return anything, then use void keyword. • Method Name: • It is a unique name that is used to define the name of a method. • Parameter List: • It is the list of parameters separated by a comma. • It contains the data type and variable name. • If the method has no parameter, left the parentheses blank. • Method Body: • It contains all the actions to be performed enclosed within the curly braces. 28 Method Declaration
  • 29. • Example int multi (int a, int b) { // method body; return (a*b); } • Example void add() { // method body; } 29 Method sample example
  • 30. • There are two types of methods in Java: • Predefined Method • User-defined Method 30 Method Types
  • 31. • Predefined Method • The method that is already defined in the Java class libraries is known as predefined methods. • It is also known as the standard library method or built-in method. • We can directly use these methods just by calling them in the program at any point. • Some pre-defined methods are • length(), equals(), compareTo(), sqrt(), etc. • When we call any of the predefined methods in our program, a series of codes related runs in the background that is already stored in the library. 31 Predefined Method
  • 32. public class Demo { public static void main(String[] args) { // using the max() method of Math class System.out.print("The maximum number is: " + Math.max(9,7)); } } 32 Method Types
  • 33. • The method written by the user or programmer is known as a user- defined method. • These methods are modified according to the requirement. • Example int EvenOdd(int num) { //method body if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } 33 User-defined Method
  • 34. import java.util.Scanner; public class EvenOdd { public static void main (String args[]) { Scanner scan=new Scanner(System.in); System.out.print("Enter the number: "); //reading value from the user int num=scan.nextInt(); //method calling findEvenOdd(num); } 34 User-defined Method
  • 35. class Rectangle { double l; double b; // display area of a rectangle void area() { System.out.print(“Area is "); System.out.println(l * b ); } } 35 Method Example Program to display area of Rectangle using method.
  • 36. class BoxDemo { public static void main(String args[]) { Rectangle mybox1 = new Rectangle(); Rectangle mybox2 = new Rectangle(); // assign values to mybox1's instance variables mybox1.l = 10; mybox1.b = 20; mybox2.l = 3; /* assign different values to mybox2's instance variables */ mybox2.b = 6; mybox1.area(); // display volume of first box mybox2.area(); // display volume of second box } } 36 Method Example
  • 37. • If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. • If we have to perform only one operation, having same name of the methods increases the readability of the program. • Advantage of method overloading • Method overloading increases the readability of the program. • Different ways to overload the method • There are two ways to overload the method in java • By changing number of arguments • By changing the data type 37 Method Overloading
  • 38. int area(int r) { return 3.14 * r * r; } int area(int h, int l) { return h * l; } 38 Method Overloading Example
  • 39. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // Overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } 39 class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } Method Overloading Example
  • 40. • This program generates the following output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625 40 Method Overloading Example- Result
  • 41. • In Java, a constructor is a block of codes similar to the method. • It is called when an instance of the class is created. • At the time of calling constructor, memory for the object is allocated in the memory. • It is a special type of method which is used to initialize the object. • Every time an object is created using the new() keyword, at least one constructor is called. • It calls a default constructor if there is no constructor available in the class. • In such case, Java compiler provides a default constructor by default. 41 Constructor
  • 42. • It is called constructor because it constructs the values at the time of object creation. • It is not necessary to write a constructor for a class. • It is because java compiler creates a default constructor if your class doesn't have any. • Rules for creating Java constructor • There are two rules defined for the constructor. • Constructor name must be the same as its class name • A Constructor must have no explicit return type • A Java constructor cannot be abstract, static, final. 42 Constructor
  • 43. • There are two types of constructors in Java: • Default constructor (no-arg constructor) • Parameterized constructor • Java Default Constructor • A constructor is called "Default Constructor" when it doesn't have any parameter. • Syntax of default constructor: <class_name>(){} • The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type. 43 Constructor Types
  • 44. • Java Parameterized Constructor • A constructor which has a specific number of parameters is called a parameterized constructor. • The parameterized constructor is used to provide different values to distinct objects. • However, you can provide the same values also. • Example Student(int i,String n){ id = i; name = n; } 44 Constructor Types
  • 45. 45 class Bike1{ //creating a default constructor Bike1() { System.out.println("Bike is created"); } public static void main(String args[]) { //calling a default constructor Bike1 b=new Bike1(); } } class Student { int id; String name; void display() { System.out.println(id+" "+name); } public static void main(String args[]) { Student s1=new Student(); Student s2=new Student(); //displaying values of the object s1.display(); s2.display(); } } Constructor Example
  • 46. 46 class Student4{ int id; String name; //creating a parameterized constructor Student4(int i,String n) { id = i; name = n; } void display() { System.out.println(id+" "+name); } public static void main(String args[]) { //creating objects and passing values Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } } Parameterized Constructor Example
  • 47. • Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. • They are arranged in a way that each constructor performs a different task. • They are differentiated by the compiler by the number of parameters in the list and their types. 47 Constructor Overloading in Java
  • 49. 49
  • 50. • In Java, this is a reference variable that refers to the current object. • Usage of Java this keyword • this can be used to refer current class instance variable. • this can be used to invoke current class method (implicitly) • this() can be used to invoke current class constructor. • this can be passed as an argument in the method call. • this can be passed as argument in the constructor call. • this can be used to return the current class instance from the method. 50 this keyword in Java
  • 51. class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ rollno=rollno; name=name; fee=fee; } void display(){ System.out.println(rollno+" "+name+" "+fee); } } 51 Program without this keyword class TestThis { public static void main(String args[]) { Student s1=new Student(111,“Ankit",5000f); Student s2=new Student(112,“Sumit",6000f); s1.display(); s2.display(); } }
  • 52. 52 0 null 0.0 0 null 0.0 • Parameters (formal arguments/local veriables) and instance variables are same. • So, need to use this keyword to distinguish local variable and instance variable. Program output
  • 53. class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ this.rollno=rollno; this.name=name; this.fee=fee; } void display(){ System.out.println(rollno+" "+name+" "+fee); } } 53 Program with this keyword class TestThis { public static void main(String args[]) { Student s1=new Student(111,“Ankit",5000f); Student s2=new Student(112,“Sumit",6000f); s1.display(); s2.display(); } }
  • 54. class Student{ int rollno; String name; float fee; Student(int r, String n, float f){ rollno=r; name=n; fee=f; } void display(){ System.out.println(rollno+" "+name+" "+fee); } } 54 Program without this keyword class TestThis { public static void main(String args[]) { Student s1=new Student(111,“Ankit",5000f); Student s2=new Student(112,“Sumit",6000f); s1.display(); s2.display(); } }
  • 55. • The static keyword in Java is used for memory management mainly. • The static keyword belongs to the class than an instance of the class. • The static can be: • Variable (also known as a class variable) • Method (also known as a class method) • Nested class • If you declare any variable as static, it is known as a static variable. 55 static keyword in Java
  • 56. • It makes your program memory efficient (i.e., it saves memory). • Understanding the problem without static variable class Student{ int rollno; String name; String college=“DYP-ATU"; } • Suppose there are 500 students in my college. • Now all instance data members will get memory each time when the object is created. • "college" refers to the common property of all objects. • If we make it static, this field will get the memory only once. 56 static keyword in Java
  • 57. 57 class Student{ int rollno; //instance variable String name; static String college =“DYP"; //static variable Student(int r, String n) { //constructor rollno = r; name = n; } void display () { System.out.println(rollno+" "+name+" "+college); } } public class TestStatic { public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); //Student.college=“DYP"; s1.display(); s2.display(); } } static keyword Example