•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
DeclaringClasses
class class_name
{
type variable;
type method1();
type method2(parameter-
list);
}
Class_name
variable/attributes;
intnumber;
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 bodysurrounded 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
classStudent {
intid; //fieldordatamemberorinstancevariable
Stringname;
//creatingmainmethodinsidetheStudentclass
publicstaticvoidmain(Stringargs[])
{
//Creatinganobjectorinstance
Students1=newStudent(); //creatinganobjectofStudent
//Printingvaluesoftheobject
System.out.println(s1.id);
//accessingmemberthroughreferencevariable
System.out.println(s1.name);
}
}
13
classStudent
{
intid;
Stringname;
}
//CreatinganotherclassTestStudentwhichcontainsthemainmethod
classTestStudent
{
publicstaticvoidmain(Stringargs[])
{
Students1=newStudent();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Class and object Example
classStudent
{
intid;
Stringname;
}
classTestStudent
{
publicstaticvoidmain(Stringargs[])
{
Students1=newStudent();
Students2=newStudent();
14
//Initializingobjects
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 methodis a way to perform some task.
•The method in Javais a collection of instructions that performs a specific
task.
•A methodis
•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 reusabilityof 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 modificationand readabilityof 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 newkeyword.
•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 methodor 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
•The method written by the user or programmer is known as a user-
definedmethod.
•These methods are modified according to the requirement.
•Example
intEvenOdd(intnum)
{//methodbody
if(num%2==0)
System.out.println(num+"iseven");
else
System.out.println(num+"isodd");
}
33
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(inta) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(inta, intb) {
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
ConstructorTypes
•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(inti,Stringn){
id=i;
name=n;
}
44
Constructor Types
•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
classStudent{
introllno;
Stringname;
floatfee;
Student(introllno,Stringname,floatfee){
rollno=rollno;
name=name;
fee=fee;
}
voiddisplay(){
System.out.println(rollno+""+name+""+fee);
}}
51
Program without this keyword
classTestThis
{
publicstaticvoidmain(Stringargs[])
{
Students1=newStudent(111,“Ankit",5000f);
Students2=newStudent(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
classStudent{
introllno;
Stringname;
floatfee;
Student(introllno,Stringname,floatfee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
voiddisplay(){
System.out.println(rollno+""+name+""+fee);
}}
53
Program with this keyword
classTestThis
{
publicstaticvoidmain(Stringargs[])
{
Students1=newStudent(111,“Ankit",5000f);
Students2=newStudent(112,“Sumit",6000f);
s1.display();
s2.display();
}
}
classStudent{
introllno;
Stringname;
floatfee;
Student(intr, Stringn, floatf){
rollno=r;
name=n;
fee=f;
}
voiddisplay(){
System.out.println(rollno+""+name+""+fee);
}}
54
Program without this keyword
classTestThis
{
publicstaticvoidmain(Stringargs[])
{
Students1=newStudent(111,“Ankit",5000f);
Students2=newStudent(112,“Sumit",6000f);
s1.display();
s2.display();
}
}
•The static keywordin 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
classStudent{
introllno;
Stringname;
Stringcollege=“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