CSE211 Lecture 7

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

Object and Class

1
Object
 Java is a true object oriented language and therefore the underlying
structure of all Java programs is classes. Anything we wish to
represent in a Java program must be encapsulated in a class that
defines the state and behavior of the basic program.
 Any entity that has state and behavior is known as an object. i.e. a
chair, pen, table, keyboard, bike, etc. It can be physical or logical.
 An Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory. Objects
can communicate with one another.

2
Object
 The state of an object consists of a set of data fields (also known
as properties) with their current values.
 The behavior of an object is defined by a set of methods.
Example: A dog is an object because it has states like color, name,
breed, etc. as well as behaviors like wagging the tail, barking, eating,
etc

3
Class
 A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical
entity not physical.
 A class defines a set of attributes and behaviors that are common
to all objects of that class, and objects created from that class
inherit these attributes and behaviors. This allows for a more
organized and efficient way of representing real-world objects and
their properties in a program.

4
Class
 For example, you could have a class called "Car" that defines the
attributes of a car such as make, model, year, and color, as well as
behaviors such as starting the engine and driving. Each individual
car that you create from the Car class would have its own unique
values for the attributes, but they would all inherit the same
behaviors defined in the class.
 In this way, classes serve as a logical abstraction, allowing you to
represent complex real-world objects in a clear and organized
manner, without having to specify all of their details every time
you create an instance of the object.
5
Object & Class
Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

6
Class declaration
 A class is a template for manufacturing objects. You
declare a class by specifying the class keyword
followed by a non-reserved identifier that names it. A
pair of matching open and close brace characters
({ and }) follow and delimit the class's body.

 A class's body is populated with fields, methods, and


constructors. Combining these language features into
classes is known as encapsulation.
7
Multi-class applications and main()
 A Java application is implemented by one or more
classes. Small applications can be accommodated by a
single class, but larger applications often require
multiple classes. In that case one of the classes is
designated as the main class and contains
the main() entry-point method.

8
Declaring Object Reference Variables
To reference an object, assign the object to a reference
variable.

To declare a reference variable, use the syntax:

ClassName objectRefVar;

Example:
Circle myCircle;

9
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
Assign object reference Create an object
Example:
Circle myCircle = new Circle();

The new operator dynamically allocates (that is, allocates at run


time) memory for an object and returns a reference to it. This
reference is then stored in the variable. Thus, in Java, all class objects
must be dynamically allocated. 10
Accessing Objects
 Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius

 Invoking the object’s method:


objectRefVar.methodName(arguments)
e.g., myCircle.getArea()

To access these variables, you will use the dot (.) operator.
The dot operator links the name of the object with the name
of an instance variable.
11
Simple Example of Object and Class
1.class Student{
2. //defining fields
3. int id; //field or data member or instance variable
4. String name;
5. //creating main method inside the Student class
6. public static void main(String args[]){
7. //Creating an object or instance
8. Student s1=new Student(); //creating an object of Student
9. //Printing values of the object
10. System.out.println(s1.id); //accessing member through reference variable
11. System.out.println(s1.name);
12. }
13.}

Output:
The new keyword is used to allocate
0
memory at runtime
null

12
Default Value for a Data Field
The default value of a data field is null for a String
type, 0 for a numeric type, false for a boolean type,
empty character for a char type, 0.0 for float and
double type. However, Java assigns no default
value to a local variable inside a method.

13
Java Program to demonstrate having the
main method in another class
1.class Student{
2. int id;
3. String name;
4.}
5.//
Creating another class TestStudent1 which contains the main method
6.class TestStudent1{
7. public static void main(String args[]){
8. Student s1=new Student();
9. System.out.println(s1.id);
10. System.out.println(s1.name);
11. }
12.}

It is a better approach than previous one.


14
3 Ways to initialize object

 There are 3 ways to initialize object in java.


– By reference variable
– By method
– By constructor

15
3 Ways to initialize object
Initialization through reference
1.class Student{
2. int id;
3. String name;
4.}
5.class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. s1.id=101;
12. s1.name=“Rahim"; Output:
13. s2.id=102; 101 Rahim
14. s2.name=“Samia"; 102 Samia
15. //Printing data
16. System.out.println(s1.id+" "+s1.name);
17. System.out.println(s2.id+" "+s2.name);
18. }
19.}

16
3 Ways to initialize object
Initialization through method
1.class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9.}
10.class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(101,“Rahim"); Output:
15. s2.insertRecord(102,“Samia"); 101 Rahim
16. s1.displayInformation(); 102 Samia
17. s2.displayInformation();
18. }
19.}

17
Constructor in Java

 Constructor in java is a special type of method that is


used to initialize the object.

 Java constructor is invoked at the time of object


creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.

18
Constructor in Java

 Rules for creating java constructor


– There are basically two rules defined for the
constructor.
 Constructor name must be same as its class name
 Constructor must have no explicit return type

19
Constructor in Java

 Types of java constructors


– There are two types of constructors:
 Default constructor (no-arg constructor)
 Parameterized constructor

20
Java Default Constructor
 A constructor that have no parameter is known as default constructor.

class Bike1{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created
 Rule: If there is no constructor in a class, compiler
automatically creates a default constructor. 21
Java parameterized constructor

 A constructor that have parameters is known as


parameterized constructor.

 Why use parameterized constructor?


– Parameterized constructor is used to provide different values
to the distinct objects

22
Example of parameterized constructor
class Student4{
int id;
String name;

Student4(int i, String n){


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

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
} 23
Constructor Overloading in Java

 Constructor overloading is a technique in Java in


which a class can have any number of constructors
that differ in parameter lists.

 The compiler differentiates these constructors by


taking into account the number of parameters in the
list and their type.

24
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i, String n){
id = i;
name = n;
}
Student5(int i, String n, int a){
id = i; Output:
name = n; 111 Karan 0
age=a; 222 Aryan 25
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
} }

25
Difference between constructor and
method in java
Java Constructor Java Method

Constructor is used to initialize the Method is used to expose behaviour


state of an object. of an object.

Constructor must not have return Method may or may not have return
type. type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default Method is not provided by compiler


constructor if you don't have any in any case.
constructor.

Constructor name must be same as Method name may or may not be


the class name. same as class name.

26
Java Copy Constructor

 There is no copy constructor in java. But, we can copy


the values of one object to another like copy
constructor in C++.
 There are many ways to copy the values of one object
into another in java. They are:
– By constructor
– By assigning the values of one object into another

27
Copying values with constructor
class Student6{
int id;
String name;

Student6(int i,String n){


id = i;
name = n;
}
Student6(Student6 s){
id = s.id; In this example, we are
name =s.name; going to copy the values
} of one object into
void display(){System.out.println(id+" "+name);} another using java
constructor.
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan"); Output:
Student6 s2 = new Student6(s1);
s1.display();
s2.display(); 111 Karan
} 111 Karan
} 28
Copying values without constructor
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n; We can copy the values
} of one object into
Student7(){} another by assigning the
void display(){System.out.println(id+" "+name);} objects values to
another object. In this
public static void main(String args[]){ case, there is no need to
Student7 s1 = new Student7(111,"Karan"); create the constructor.
Student7 s2 = new Student7();
s2.id=s1.id; Output:
s2.name=s1.name;
s1.display(); 111 Karan
s2.display(); 111 Karan
}
} 29
Creating multiple objects by one type
only
 Each object has its own copies of the instance variables.
This means that if you have two Box objects, each has
its own copy of depth, width, and height.

 It is important to understand that changes to the instance


variables of one object have no effect on the instance
variables of another.

30
Creating multiple objects by one type
1.class Rectangle{
only
2. int length;
3. int width;
4. void insert(int l, int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){System.out.println(length*width);}
9.}
10.class TestRectangle1{
11. public static void main(String args[]){
12. Rectangle r1=new Rectangle();
13. Rectangle r2=new Rectangle();
14. r1.insert(11,5);
15. r2.insert(3,15);
16. r1.calculateArea();
17. r2.calculateArea(); Output:
18.}
19.} 55
45

31
Creating multiple objects by one type only

32
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
 You might think that b2 is being assigned a reference to a copy
of the object referred to by b1. That is, you might think that
b1 and b2 refer to separate and distinct objects.

 However, this would be wrong. Instead, after this fragment


executes, b1 and b2 will both refer to the same object.

 The assignment of b1 to b2 did not allocate any memory or copy


any part of the original object. It simply makes b2 refer to the
same object as does b1. Thus, any changes made to the object
through b2 will affect the object to which b1 is referring,
since they are the same object. 33
Differences between Variables of
Primitive Data Types and Object Types
Created using new Circle()
Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle

radius = 1

34
Copying Variables of Primitive
Data Types and Object Types
Primitive type assignment i = j

Before: After:

i 1 i 2

j 2 j 2

Object type assignment c1 = c2

Before: After:

c1 c1

c2 c2

c1: Circle C2: Circle c1: Circle C2: Circle


radius = 5 radius = 9 radius = 5 radius = 9

35
Garbage Collection
As shown in the previous figure, after the assignment statement
c1 = c2, c1 points to the same object referenced by c2. The
object previously referenced by c1 is no longer referenced. This
object is known as garbage. Garbage is automatically collected
by JVM.

TIP: If you know that an object is no longer needed, you can


explicitly assign null to a reference variable for the object.
The JVM will automatically collect the space if the object is
not referenced by any variable.

36
Java Object as parameter

This program
generates the
following output:
ob1 == ob2: true
ob1 == ob3: false

37
Java Object as parameter
 When you pass an object to a method, the situation
changes dramatically, because objects are passed by
what is effectively call-by-reference.
 Keep in mind that when you create a variable of a class
type, you are only creating a reference to an object. Thus,
when you pass this reference to a method, the parameter
that receives it will refer to the same object as that
referred to by the argument.
 This effectively means that objects act as if they are
passed to methods by use of call-by-reference. Changes to
the object inside the method do affect the object used as
an argument. For example, consider the following
program:
38
This program generates the
following output:

ob.a and ob.b before call: 15 20


ob.a and ob.b after call: 30 10

In this case, the actions inside meth(


) have affected the object used as an
argument.

39
class Operation2{
int data=50;

void change(Operation2 op){


op.data=op.data+100;// In case of call by
changes will be in the instance variable reference original value
} is changed if we made
public static void main(String args[]){ changes in the called
Operation2 op=new Operation2(); method.

System.out.println("before change "+op.data); If we pass object in


place of any primitive
op.change(op);//passing object
value, original value will
System.out.println("after change "+op.data);
be changed. In this
} example we are passing
} object as a value.
40
Returning Objects

 A method can return any type of data, including class


types that you create. For example, in the following
program, the incrByTen( ) method returns an object
in which the value of a is ten greater than it is in the
invoking object.

41
The output generated by this program
is shown here:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22

each time incrByTen( ) is invoked, a


new object is created, and a reference
to it is returned to the calling routine.

42

You might also like