0% found this document useful (0 votes)
7 views33 pages

CSBP219 SP25 Oop LN2

The document covers user-defined classes in programming, focusing on concepts such as assignment operators, deep and shallow copying, copy constructors, and the use of keywords like 'this' and 'static'. It includes practical examples and exercises related to creating and manipulating objects, comparing them, and understanding static members. Additionally, it introduces UML class diagrams and provides exercises for implementing a Car class and tracing programs.

Uploaded by

banana80milk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views33 pages

CSBP219 SP25 Oop LN2

The document covers user-defined classes in programming, focusing on concepts such as assignment operators, deep and shallow copying, copy constructors, and the use of keywords like 'this' and 'static'. It includes practical examples and exercises related to creating and manipulating objects, comparing them, and understanding static members. Additionally, it introduces UML class diagrams and provides exercises for implementing a Car class and tracing programs.

Uploaded by

banana80milk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

User Defined Classes

Continued
Chapter Objectives
 Learn about assignment operators, deep and shallow
copy, copy constructors and how to perform
comparison on objects
 Learn the significance of the keywords “this”, and
“static”
 Learn about UML Class Diagrams
Objects and Assignment Operator
Clock myClock = new Clock(10,28,45);
Clock yourClock = new Clock(7,27,36);
Objects and Assignment Operator
myClock = yourClock; //shallow copy

• Copies the value of the reference variable yourClock into


the reference variable myClock
• After this statement executes, both yourClock and
myClock refer to the same object
Objects and Assignment Operator
• Shallow copying: two or more reference variables of
the same type point to the same object

• Deep copying: each reference variable refers to its


own object
Deep Copy
//In public class Clock
//deep copy
public void makeCopy(Clock otherClock)
{
hr = otherClock.hr;
min = otherClock.min;
sec = otherClock.sec;
}

//to use it
clock2.makeCopy(clock1);
//this will copy clock1 to clock2
The Copy Constructor
 Executes when an object is instantiated
 Initialized using an existing object
//In public class Clock
public Clock(Clock otherClock)
{
hr = otherClock.hr;
min = otherClock.min;
sec = otherClock.sec;
}
//to use it
Clock clock3 = new Clock(clock2);
//this will create a new clock (clock3)
//and initialize it with clock2
In Class Exercise – 1
Shallow and Deep Copy
https://onlinegdb.com/VsEo0p6Im
public class TestClock2 { public class TestClock3 {
public static void main(String[] args) public static void main(String[] args)
{ {
1. Clock clock1 = new Clock(); 1. Clock clock1 = new Clock();
2. Clock clock2 = new Clock(11, 12, 15);
3. Clock1 = clock2; 2. Clock clock2 = new Clock(11, 12, 15);
3. Clock1 = new Clock(clock2);
4. //what are the hr,min,sec of clock1?
5. System.out.println(clock1); 4. //what are the hr,min,sec of clock1?
5. System.out.println(clock1);
6. //see the side effect
7. clock1.setHr(5);
6. //see the side effect
8. //what are the values of clock1? 7. clock1.setHr(5);
9. System.out.println(clock1); 8. //what are the values of clock1?
9. System.out.println(clock1);
10. //what are the values of clock2?
10. //what are the values of clock2?
11. System.out.println(clock2);
} 11. System.out.println(clock2);
} }
}

• Why are the outputs different?


• What would be the output if we used
• clock1.makecopy(clock2);
• Instead of clock1 = new Clock(clock2)
Relational Operators and Arrays
• if (listA == listB)...
• The expression listA == listB determines if the
values of referneces in listA and listB are the same
• To determine whether listA and listB contain the
same elements, you need to compare them
component by component
Class MyArrays{
public static boolean isEqualArrays(int[] arr1, int[] arr2){
1. if (arr1 == arr2 ) return true;
2. if (arr1.length != arr2Array.length) return false;
3. for (int i = 0; i < arr1.length; i++){
4. if (arr1[i] != arr2[i])return false;
5. }
6. return true;
7. }//end of method
}//end of class
9
Comparing Objects
 Shallow and Deep Comparison

String str1 = new String("Hello");


String str2 = new String("World");

How do you test if str1 and str2 are the


same or not?
What is the difference between using
equals() ? compareTo() ? and == ?
Exercise - 2
 Write the copy constructor
public Clock(Clock other){

 Write the equals method in the class Clock


public boolean equals(Clock other){

 Write the compareTo() method in the class Clock


public int compareTo(Clock other){

https://onlinegdb.com/nx31Nc9QB
//main
Clock ckTest = new Clock(10, 30, 20);
Sys.. (ckTest.getHr() ) ;
The “this” Keyword
 A class can use “this” to access its own members
(variables/methods)
//Class Clock
public int getHr(){ return this.hr;}
public int getMin(){ return this.min;}
public int getSec() { return this.sec;}

 Why?
 Sometimes just to avoid confusion
this Keyword
public class Foo{
//variables
private int x;
public Foo(int v) // What happens if you remove
{ // the word this
this.set(v); //OP //Will it work?
}
//methods public void set(int x)
public void set(int v) {
{ this.x = x;
this.x = v; //OP }

}
}
This(..) Keyword
 this() refers to the constructor
public class MC{
What is the output of the following code?
//variables
public int x;
public class Test{
//methods
public static void main(String[] args){
public MC(){
1. MC mc = new MC(10);
this(5);
2. MC mc2 = new MC();
}
3. System.out.println(mc2.x+”,”+mc.x);
public MC(int v){
4. mc = mc2.inc();
this.x = v;
5. System.out.println(mc2.x+”,”+mc.x);
}
}
public MC inc(){
}
this.x++;
return this;
} Output (1) : Output (2) :
} A) 0, 10 A) 1, 10
B) 5, 10 B) 6, 10
C) 10, 5 C) 5, 11
D) 5, 5 D) 6, 6
Review Questions

1. public class Clock{


2. //variables
3. public int hr=1, min, sec;
4.
5. //methods
What will be the value of hr after these
6. public Clock(){this(5);}
statement?
7. public Clock(int hr){
8. this.hr = hr ;
Clock c1 = new Clock();
9. }
Clock c2 = new Clock(10);
10.}
a. c1.hr = 10, c2.hr = 10
b. c1.hr = 5, c2.hr = 10
c. c1.hr = 1, c2.hr = 10
The “this” Keyword
 this (followed by dot) ➔ refers to member var. or method
 this (with circular brackets ) ➔ refers to one of the constructors
 this (alone) ➔ refers to an object
The Modifier static
 In the method heading, it specifies that the method
can be invoked by using the name of the class
 If used to declare data member, data member invoked
by using the class name
 Static data members of class exist even when no object
of class type instantiated
 Static variables are initialized to their default values
 Static methods cannot access non-static variables and non-
static methods but non-static methods can access static
variables and methods
The Modifier static
static method:
 can access only static members (Variables and Methods).
 cannot access non-static members (Variables and
Methods).
 can be invoked by class name.
 can be invoked by object name.

non-static method:
 can access static members (Variables and Methods).
 can access non-static members (Variables and Methods).
 cannot be invoked by class name.
 can be invoked by object name.
The Modifier static
static members:
 can be invoked by class name.
 can be invoked by object name.
 can be called even without having any objects
 Static Methods:
 can access only static members (Variables and Methods).
 cannot access non-static members (Variables and Methods).

non-static members :
 cannot be invoked by class name.
 can be invoked by object name.
 cannot be called without creating objects
 Non-Static Methods:
 can access static members (Variables and Methods).
 can access non-static members (Variables and Methods).
The Modifier static

numOfClocks

Class Clock

ck1 ck2 ck3


hr min sec hr min sec hr min sec
Static Members of a Class
1. public class StatEx{ 11. void setX(int a){
2. private int x; 12. x = a;
3. private static int y; 13. }
4. public static int count; 14. public String toString(){
15. return "x = " + x +
5. public StatEx(){ 16. ",y = "+ y +
6. x = 0; 17. ", count = " + count;
7. } 18. }
19. public static void incY(){
8. public StatEx(int a){ 20. y++;
9. x = a; 21. }
10. } 22. }//end class StatEx

Class Tester{
public static void main(String[] a){
StatEx sObj = new StatEx();
sObj.incY();
sObj.count++;
}}
Static Members of a Class (continued)
1. public class StatEx{
2. private int x;
StatEx sObj1 = new StatEx(3); 3. private static int y;
4. public static int count;
StatEx sObj2 = new StatEx(5);
5. public StatEx(int a){x = a;}

sObj1 sObj2

sObj1 and sObj2


Static Members of a Class (continued)
1. StatEx sObj1 = new StatEx(3);
2. StatEx sObj2 = new StatEx(5);
3. sObj2.incY(); 1. public class StatEx{
4. StatEx.count++; 2. private int x;
3. private static int y;
4. public static int count;
5. public StatEx(int a){x = a;}
11. public static void incY(){y++;}

sObj1 sObj2
Question
1. public class Student{
2. private String name;
3. private double gpa;
4. public static int count;
5.
6. public Student(String n){
7. name = n; gpa = 0;
8. count++;
9. }
10. public Student(Student s){
11. this(s.name);
12. }
13. } What is the output?
Student s1 = new Student(“Sami”);
Student s2 = new Student(“Sara”);
Student s3 = new Student(s2);
Student s4 = s1;
System.out.println (“Count =“+ Student.count); //3
System.out.println (“Count =“+ s4.count); //3
Question
What is the output?
Ahmed
Sami
Ahmed
=======================
Kamal
Sami
Kamal
=======================
Kamal
Sami
Sami
=======================
Jamal
Sami
Sami
=======================
Jamal
Jamal
Sami
Unified Modeling Language (UML)
Class Diagrams

26
Unified Modeling Language (UML)
Class Diagrams

27
Exercise - 3
Redesign exercise 2 by:
 Implementing ‘this’ keyword
 Adding static variable (numOfClocks) to count the
number of clocks created
 Test your implementation

https://onlinegdb.com/cIO5aZM8L
In Class Exercise - 4
Implement a Car Class to simulate driving:
• When constructing a Car, you supply the fuel efficiency
(Kilometer per Litre) to indicate consumption of fuel, and
the Tank Capacity to indicate the maximum fuel possible.
• Driving causes petrol level to go down and odometer to
increase.
• The class has methods for:
• add/check petrol level
• check/set the odometer (i.e., total KM driven)
• driving for a number of KM.
• Estimate driving by petrol level.
• When the car runs out of petrol, it stops.
In Class Exercise - 4
 First draw a UML diagram for the car class
 Then implement the class with the variables and
methods
 Finally implement the test class (next slide)

 Answer: https://onlinegdb.com/KhHwA-DOk
/**
In Class Exercise - 4
Test the car class
*/
public class Main{
public static void main(String [] args)
{
Car myCar = new Car(10, 70);
// 10 KM per litre , 70 litres capacity

myCar.addPetrol(20); //add 20 litres


myCar.drive(10); // drive 10 km
myCar.drive(10); // drive 10 km
myCar.addPetrol(20); //add 20 litres

System.out.print("Petrol left (in litres): ");


System.out.println(myCar.getPetrolLevel());

System.out.print("Expected Drive Remain: ");


System.out.println(myCar.estimateDrive());

System.out.print("KM driven: ");


System.out.println(myCar.getOdometer());
}
}
In Class Exercise - 5
 Trace the following program

 Code: https://onlinegdb.com/u_Z_ihLh-
In Class Exercise - 6
 Trace the following program

 Code: https://onlinegdb.com/VLzd5Mp1X

You might also like