Object
• 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
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. 2
Object Definition and Example
• 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
Class
• 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
• 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
5
6
7
Class components
• 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
Declaring Classes
Class_name
class class_name {
class structure
type instance_variable1;
variable/attributes;
int number; type instance_variable2;
float marks; type method_name1(parameter-list)
method() {
class declaration add();
// body of method
class class_name
}
{
type variable;
type method_name2(parameter-list)
type method1(); {
type method2(parameter-list); // body of method
} }
} 9
Declaring Classes
• 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
Object Creation for a class
• 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
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);
}
}
12
Class and object Example
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);
}
} 13
Class and object Example
class Student //Initializing objects
{ s1.id=101;
int id; s1.name=“Mahesh";
String name; s2.id=102;
} s2.name="Amit";
class TestStudent System.out.println(s1.id+" "+s1.name);
{
public static void main(String args[]) System.out.println(s2.id+" "+s2.name);
{
Student s1=new Student(); }
Student s2=new Student(); }
14
Method: Definition
• 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 : Uses
• 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 Declaration
• This is the general form of a method declaration:
type name(parameter-list)
{ // body of method
}
17
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;
}
18
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
}
19
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;
20
Class of Circle cont.
• aCircle, bCircle simply refers to a Circle object, not an object itself.
aCircle bCircle
null null
Points to nothing (Null Reference) Points to nothing (Null Reference)
21
Creating objects of a class
• Objects are created dynamically using the new keyword.
• aCircle and bCircle refer to Circle objects
aCircle = new Circle() ; bCircle = new Circle() ;
22
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
Before Assignment Before Assignment
aCircle bCircle aCircle bCircle
P Q P Q
23
Automatic garbage collection
• The object Q 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.
24
Accessing 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
25
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();
26
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);
}
} 27
Method Declaration
• 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 sample example
• Example
int multi (int a, int b)
{ // method body;
return (a*b);
}
• Example
void add()
{ // method body;
}
29
Method Types
• There are two types of methods in Java:
• Predefined Method
• User-defined Method
30
Predefined Method
• 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
Method Types
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
User-defined Method
• 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
Method Example
Program to display area of Rectangle using 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
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 Overloading
• 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 Example
int area(int r)
{
return 3.14 * r * r;
}
int area(int h, int l)
{
return h * l;
}
38
Method Overloading Example
class OverloadDemo { class Overload {
void test() {
System.out.println("No parameters"); public static void main(String args[]) {
} OverloadDemo ob = new OverloadDemo();
// Overload test for one integer parameter.
void test(int a) { double result;
System.out.println("a: " + a); ob.test();
}
// Overload test for two integer parameters. ob.test(10);
void test(int a, int b) { ob.test(10, 20);
System.out.println("a and b: " + a + " " + b);
}
result = ob.test(123.25);
// Overload test for a double parameter System.out.println("Result of ob.test(123.25):
double test(double a) { " + result);
System.out.println("double a: " + a);
return a*a; }
}
} }
39
Method Overloading Example- Result
• 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
Constructor
• 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 Types
• 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 Example
class Bike1{ class Student {
//creating a default constructor int id;
Bike1() String name;
{ void display() {
System.out.println("Bike is created"); System.out.println(id+" "+name);
} }
public static void main(String args[]) public static void main(String args[]) {
{ Student s1=new Student();
//calling a default constructor Student s2=new Student();
Bike1 b=new Bike1(); //
} displaying values of the object
} s1.display();
s2.display();
}
} 45
Parameterized Constructor Example
class Student4{
int id;
public static void main(String args[])
String name;
{
//creating a parameterized constructor
//creating objects and passing values
Student4(int i,String n)
{
Student4 s1 = new Student4(111,"Karan");
id = i;
Student4 s2 = new Student4(222,"Aryan");
name = n;
}
s1.display();
s2.display();
void display()
}
{
}
System.out.println(id+" "+name);
}
46
Constructor Overloading in Java
• 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 Example
48
49
this keyword in Java
• 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
Program without this keyword
class Student{
int rollno; class TestThis
String name; {
float fee; public static void main(String args[])
Student(int rollno,String name,float fee){ {
rollno=rollno;
Student s1=new Student(111,“Ankit",5000f);
name=name;
Student s2=new Student(112,“Sumit",6000f);
fee=fee;
} s1.display();
void display(){ s2.display();
System.out.println(rollno+" "+name+" "+fee); }
} }
}
51
Program output
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.
52
Program with this keyword
class Student{
int rollno; class TestThis
String name; {
float fee; public static void main(String args[])
Student(int rollno,String name,float fee){ {
this.rollno=rollno;
Student s1=new Student(111,“Ankit",5000f);
this.name=name;
Student s2=new Student(112,“Sumit",6000f);
this.fee=fee;
} s1.display();
void display(){ s2.display();
System.out.println(rollno+" "+name+" "+fee); }
} }
}
53
Program without this keyword
class Student{
int rollno; class TestThis
String name; {
float fee; public static void main(String args[])
Student(int r, String n, float f){ {
rollno=r;
Student s1=new Student(111,“Ankit",5000f);
name=n;
Student s2=new Student(112,“Sumit",6000f);
fee=f;
} s1.display();
void display(){ s2.display();
System.out.println(rollno+" "+name+" "+fee); }
} }
}
54
static keyword in Java
• 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 Example
class Student{ public class TestStatic
int rollno; //instance variable {
String name; public static void main(String args[]){
static String college =“DYP"; //static variable Student s1 = new Student(111,"Karan");
Student(int r, String n) { //constructor Student s2 = new Student(222,"Aryan");
rollno = r;
name = n; //Student.college=“DYP";
}
void display () s1.display();
s2.display();
{ System.out.println(rollno+" "+name+" "+college }
); }
}
}
57
End of Unit
58