0% found this document useful (0 votes)
168 views75 pages

3.classes and Obj

The document discusses classes and objects in programming. It explains that a class is a template used to create objects, and defines an object as any real-world entity with state and behavior. The document then covers class diagrams, defining a class, instantiating objects from a class, initializing instance variables through reference variables, methods, and constructors using the this keyword. Code snippets are provided to demonstrate these concepts.

Uploaded by

Manoj Manu
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)
168 views75 pages

3.classes and Obj

The document discusses classes and objects in programming. It explains that a class is a template used to create objects, and defines an object as any real-world entity with state and behavior. The document then covers class diagrams, defining a class, instantiating objects from a class, initializing instance variables through reference variables, methods, and constructors using the this keyword. Code snippets are provided to demonstrate these concepts.

Uploaded by

Manoj Manu
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/ 75

Classes & Objects

What you’ll learn

● Introduction to class and object


● Class diagram
● Class instantiation
● Memory level operations for class & object
● Ways to initialize the instance class members
● Basics of constructors
● this keyword
● Code snippets
● Real time demonstration
Can you name your favorite cricketer?
Describe your favorite cricketer
Segregate the nouns & verbs
List them down

Mahendra Singh Dhoni Batting


39 Years Wicket Keeping
Brown Leading the team
Batsman Strategic decision making
Indian Focus & determining
Let’s get technically started!
Class and object

What is Class?
● A class is a template or blueprint that For Example:
is used to create objects. A car is an object. It has states
● A class consists of data members and (name, color, model) and its
methods. behavior (changing gear, applying
brakes).
What is Object?
● Any real-world entity that has state
and its behavior.
Class & object

● A blueprint from which you can


create an individual object
● Any entity that has:
○ State
○ Behavior
○ Identity
● State --> data member
● Behavior --> method
● Identity --> unique Id(name)
Class diagram
Compartments

Class Name

Class Variables

Class Methods
Defining a class

● Access modifiers: A class can be public or default


● class keyword: class keyword is used to create a class.
● Class name: The name should begin with an initial letter ( refer naming
convention).
● Body: The class body surrounded by braces, { }.
Cricketer

class Cricketer{ void cricketerDetails(){

//Instance variables System.out.println(name);

String name = “Dhoni”; System.out.println(age);

int age = 39; System.out.println(color);

String color = “Brown”; System.out.println(role);

String role = “Batsman”; System.out.println(nationality);

String nationality = “Indian”; }//end of method


}//end of class
Class Instantiation

● Object is an instance of a class


● Process of creating an object from a class is called instantiation.
● Now that you have defined a new class type --> Cricketer, it is time to instantiate
an object of that type.
● new keyword is used to initialize/create an object.
● new operator is followed by a call to a constructor, which initializes the new
object.

Example: name = Dhoni


Cricketer c = new Cricketer(); age = 39
color = Brown
role = Batsman c
nationality = Indian

Heap area
Create an object
Cricketer - code snippet

class Cricketer{ public static void main(String args[]){


String name = “Dhoni”; System.out.println(“main method
int age = 39; started”);
String color = “Brown”; Cricketer c = new Cricketer();
String role = “Batsman”; c.cricketerDetails();
String nationality= “Indian”; System.out.println(“main method
void cricketerDetails(){ ended”);
System.out.println(name); }//end of main method
System.out.println(age); }//end of Cricketer class
System.out.println(color);
System.out.println(role);
System.out.println(nationality);
}//end of criketerDetails method
Create an object
Cricketer - code snippet
Create an object
Know the difference!

Example:01 Example:02
public class Demo{ public class Demo {
int x; int x;
} public static void main(String[] args) {
Demo myObj1 = new Demo();
class TestDemo{ Demo myObj2 = new Demo();
public static void main(String[] myobj1.x = 24;
args) { myobj2.x = 55;
Demo myObj = new Demo(); System.out.println(myObj1.x);
myobj.x = 40; System.out.println(myObj2.x);
System.out.println(myObj.x); }
} }
}
Ways to initialize the instance variables

● By reference variable

● By method

● By constructor
Through reference variable
By reference variable

class Student { class Main {


int id; public static void main(String args[]) {
String name; Student s1 = new Student();
} s1.id = 101;
s1.name = "John";
System.out.println(s1.id + " " + s1.name);
}
}
Through method
By method

class Student {
int rollno;
String name;
void insertRecord(int r, String n) {
rollno = r;
name = n;
}
void displayInformation() {
System.out.println(rollno + " " + name);
}
}
By method - continued.,

class Main {

public static void main(String args[])


{
Student s1 = new Student();
Student s2 = new Student();
s1.insertRecord(111, "Karan");
s2.insertRecord(222, "Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Constructor

A special method
constructs/initializes the values at the time of object creation.
No return type
Has same name as class name
Automatically invoked when the object is created
name = null
Cricketer c = new Cricketer(); object creation & age = 0
color = null
constructor
role = null
invocation nationality =
null
C
Types of constructors

● Default:
1. java compiler creates a default constructor if your class
doesn't have any explicit constructor
2. Always no-argument constructor
● User defined
1. Is explicitly written in the class
To initialize the instance members with user-defined values
1. Zero-parameterized / No-argument constructor
2. Parameterized constructor
By User defined No-arg constructor

class Employee {
int id;
String name;
float salary;
Employee() {
System.out.println(“user defined no-argument
constructor executed”);
}
void display() {
System.out.println(id + " " + name + " " + salary);
}
}
Through constructor
By user defined no-argument constructor

public class Main {


public static void main(String[] args) {

Employee e1 = new Employee();


Employee e2 = new Employee();

e1.display();
e2.display();

}
}
By User defined parameterized constructor

class Employee {
int id;
String name;
float salary;
Employee(int id, String name, float salary) {
id = id;
name = name;
salary = salary;
}
void display() {
System.out.println(id + " " + name + " " +
salary);
}
}
Through constructor
Passing values for parameterized constructor

public class Main {


public static void main(String[] args) {

Employee e1 = new Employee(101, "ajeet", 45000);


Employee e2 = new Employee(102, "irfan", 25000);
Employee e3 = new Employee(103, "nakul", 55000);

e1.display();
e2.display();
e3.display();
}
}
Through constructor
“this” keyword

● Refers to the current object


● Eliminates the confusion between Instance members and parameters
which are local to the constructors / methods
Employee(int id,String name,float salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
Through constructor
“this” keyword

● “this” refers to the Employee class object


● “this” keyword is used for the instance variable
initialization
● Values passed to the constructor are local to it

● Local values --> id, name, salary


● Instance variables --> this.id, this.name,
this.salary
Through constructor
Knowledge check

Try predicting the outputs for


the given code snippets !

Ensure proper analysis of


codes before guessing the
output.
Through constructor
Knowledge check

class Company {
String name;
public static void main(String[] args) {
System.out.println(new Company().name);
}
}
Through constructor
Knowledge check

class Company {
String name;
public static void main(String[] args) {
Company c = new Company();
Company c1 = c;
c1.name = “Ethnus”;
c = null;
System.out. println(c.name);
}
}
Through constructor
Knowledge check

public class Company{


String name;
public static void main(String[] args) {
Company c1 = new Company();
c1.name = "Ethnus";
System.out.println(c1.name);
c1 = new Company();
System.out.println(c1.name);
}

}
Through constructor
Knowledge check

public class Company {


String name;
public static void main(String[] args) {
Company c1 = new Company();
c1.name = "Ethnus";
Company c2 = c1;
c1 = null;
System.out.println(c2.name);
new Company();
Company c3;
c3.name = "Ethnus";
System.out.println(c3.name);}}

}
Through constructor
Knowledge check

public class Program1 {


String name;
void changeRef(Program1 that) {
that = this;
System.out.println(this.name);
}
public static void main(String[] args) {
Program1 c1 = new Program1();
c1.name = "Ethnus";
Program1 c2 = new Program1();
c2.name = "Aptimithra";
c1.changeRef(c2);
System.out.println(c1.name);
System.out.println(c2.name);}}
}
Through constructor
Knowledge check

public class Company2 {


String name;
void changeRef(Company2 that, Company2 someCompany) {
someCompany = that;
someCompany.name = this.name;
that = someCompany;}
public static void main(String[] args) {
Company2 c1 = new Company2();
c1.name = "Ethnus";
Company2 c2 = new Company2();
c2.name = "Aptimithra";
c1.changeRef(c2, c1);
System.out.println(c1.name);
System.out.println(c2.name);}}
Through constructor
Knowledge check

class Company {
String name;
void changeRef(Company that) {
that.name = this.name;
}
public static void main(String[] args) {
Company c1 = new Company();
c1.name = "Ethnus";
Company c2 = new Company();
c2.name = "Aptimithra";
c1.changeRef(c2);
System.out.println(c1.name);
System.out.println(c2.name);}
Through constructor
Knowledge check

class Company {
String name;
void changeRef(Company that) {
that.name = this.name;
that = null;
}
public static void main(String[] args) {
Company c1 = new Company();
c1.name = "Ethnus";
Company c2 = new Company();
c2.name = "Aptimithra";
c1.changeRef(c2);
System.out.println(c1.name);
System.out.println(c2.name);}
}
}
Through constructor
Code snippet

public class Main {


static int x = 10;
public static void main(String[] args) {
Main obj = new Main();
Main obj1 = new Main();
obj.x = x + 1;
System.out.println(obj.x);
System.out.println(obj1.x);
} }
Through constructor
Real time example!

● The localStorage object stores data with


no expiration date.
● The data will not be deleted when the
browser is closed.
● It will be available the next day, week, or
year.
● The localStorage property is read-only.
Through constructor
Real time example!
Through constructor
Real time example!

DEMO
Question: 01

Which of the following statement(s) is/are


correct?
X: A class is like a blue print and we can A. X only
create as many objects using that class B. Y only
Y: Every object should belong to a class, C. Both X and Y are correct
since we cannot create objects without D. Both X and Y are incorrect
a class
Question: 02

Which of the following class declaration is


correct?

/* X */ /* Y */ A. X only
class Student { CLASS Student { B. Y only
String String C. X and Y both are correct
name; name;
D. X and Y both are incorrect
int marks; int marks;
char char
section; section;
} }
Question: 03

Which of the following is a valid


declaration of an object of class Student?
1. Student obj = new Student; A. 1 only
2. Student obj = new Student();
3. obj = new Student(); B. 2 only
4. new Student obj; C. 1 & 2
D. 3 & 4
Question: 04

What will be the output of the following


program?
class Apple {
int weight; A. 1
public static void main(String args[]) { B. 2
Apple a1 = new Apple(); C. Error
Apple a2 = new Apple(); D. null
a1.weight = 1;
a2.weight = 2;
a2 = a1;
System.out.println(a2.weight);
}}
Question: 05

class Car {
int Wheels;
void swap(Car other) {
other = this; } }
public class Main { A. 48
public static void main(String[] args) { B. 44
Car C1 = new Car(); C. 84
C1.Wheels = 4; D. 88
Car C2 = new Car();
C2.Wheels = 8;
C2.swap(C1);
System.out.print(C1.Wheels + "");
System.out.print(C2.Wheels);
}
}
Question: 06

class Car {
int Wheels;
void swap(Car other) {
other.Wheels = this.Wheels;
}} A. 48
public class Main { B. 44
public static void main(String[] args) { C. 84
Car C1 = new Car(); D. 88
C1.Wheels = 4;
Car C2 = new Car();
C2.Wheels = 8;
C1.swap(C2);
System.out.println(C1.Wheels);
System.out.println(C2.Wheels);
}}
Question: 07

class A { public class Increment {


int i = 0; public static void
A(int i) { main(String[] args) {
this.i = i + A a = new A(5);
4; a.increment(); A. i=1
} a.operate(); B. i = 103
void increment() a = new A(a.i); C. i = 55
{ a.operate(); D. Compilation Error
i = this.i + a.increment();
1;
} System.out.printl
void n("i = " + a.i);
operate() }
{ }
i *= 3;
Question: 08

class Test {
int i;
}
class Main { A. 0
public static void main(String args[]) { B. Garbage Value
Test t; C. Compilation Error
System.out.println(t.i); D. Runtime Error
}
Question: 09

public class Final {


final int assign = 30;
public static void main(String[] args)
{
final int result = 20; A. 20 20 25
final int assign; B. 20 30 25
C. Compilation Error
Final f = new Final();
D. Runtime Error
assign =20;
System.out.println(assign);
System.out.println(f.assign);

System.out.println(f.process(result));
}
int process(int a) {
Question: 10

public class InitializationTest {


int number;
public void InitializationTest(int
A. 5
number) {
B. Compile time Error since no default
this.number = number;
constructor
System.out.println(number);
C. Compile time Error since no
}
parameterized constructor
public static void main(String[] args) {
D. Compilation Error or Runtime Error for
InitializationTest obj1, obj2;
some other reason
obj1 = new InitializationTest();
obj2 = new InitializationTest(5);
}
}
Question: 11

class Test {
void start() {
String stra = "do";
String strb = method(stra);
System.out.print(": " + stra + strb);
A. dogood : dogoodgood
}
B. dogood : gooddogood
String method(String stra) {
C. dogood : dodogood
stra = stra + "good";
D. dogood : dogood
System.out.print(stra);
return " good";
} }
class Main {
public static void main(String[] args) {
Test obj = new Test();
obj.start(); } }
Question: 12

class Student { class ReferencesAndObjects {


String name; public static void main(String s[]) {
int marks; Student st1 = new Student();
Student st2;
char section;
st2 = st1;
} st1.name = "Rajesh"; A. Rajesh 87 C Rajesh 87 C
st2.marks = 87; B. rajesh 87 C rajesh 87 C
st1.section = 'C'; C. Rajesh C 87 Rajesh C 87
System.out.println("" + st1.name + D. rajesh C 87 rajesh C 87
"" + st1.marks + "" + st1.section);
System.out.println("" + st2.name +
"" + st2.marks + "" + st2.section);
}}
Question: 13

class Simple { class Demo {


int a = 0; public static void main(String
void incr() { aRgs[]) {
a++; Simple s = new Simple();
} Simple r = new Simple();
void display() { s.incr(); A. a=0a=0
System.out.println(" r.incr(); B. a=1a=1
a = " + a); s.display(); C. a=0a=1
} r.display(); D. a=1a=2
}
}
Question: 14

class PrintA { class OutPut {


int printA; int c;
} public static void main(String[] args) {
class PrintB { PrintA a = new PrintA();
int printB = 5; PrintB c = new PrintB(); A. printA = 0 printB = 5 c = 0
int c; System.out.println("printA = " + B. printA = 0 printB = 5 c =
} a.printA); (some object reference
System.out.println("printB = " + value)
c.printB); C. Compilation Error
System.out.println("c = " + c.c);
D. Runtime Error
}
}
Question: 15
class Student { class ReferencesAndObjects {
String name; public static void main(String s[]) {
int marks; Student st1 = new Student();
char section; Student st2 = new Student(); A. Print using st1 : Rajesh 0 C Print
} st1 = st2; using st2 : null 87
st1.name = "Rajesh";
st2.marks = 87; A. Print using st1 : Rajesh 87 C Print
st1.section = 'C'; using st2 : Rajesh 87 C
System.out.print("Print using st1 : " +
st1.name + " " + st1.marks + " " + A. Print using st1 : null 0 Print using
st1.section); st2 : Rajesh 87 C
System.out.print("Print using st2 : " +
st2.name + " " + st2.marks + " " + A. Compilation Error
st2.section);
}}
Question: 16

class User{
int age;
String name;
} A. Error
public class Main{ B. Null pointer Exception
public static void main(String[] args) { C. 100
User u1=new User(); D. null
u1.name=100;
u1=null;

System.out.println(u1.name);
}
}
Question: 17

class User{
int age;
String name; }
public class Main{
public static void main(String[] args) { A. A
User u1=new User(); B. Null
u1.name="A"; C. Error
User u2=u1; D. C
u2=null;
u2=new User();
u1.name = "c";
u2.name=u1.name;
u1=null;
System.out.println(u2.name);
} }
Question: 18

class User{
int age;
String name;
} A. A
public class Main{ B. B
public static void main(String[] args) { C. Error
User u1=new User(); D. Cannot execute
u1.name="A";
User u2=u1;
u1.name = "B";

System.out.println(u1.name);
}
Question: 19

class User{
int age;
String name;
} A. A
public class Main{ B. Null pointer Exception
public static void main(String[] args) { C. Cannot execute
User u1=new User(); D. null
u1.name="A";
u1=null;
System.out.println(u1.name);
}
}
Question: 20

class User{
int age;
String name;
} A. A
public class Main{ B. Null pointer Exception
public static void main(String[] args) { C. Cannot execute
User u1=new User(); D. null
u1.name="A";
User u2=new User();
u2=u1;
u1=null;

System.out.println(u1.name);
Question: 21

class User{
int age;
String name;
} A. A
public class Main{ B. B
public static void main(String[] args) { C. Error
User u1=new User(); D. u1 address
u1.name="A";
User u2=u1;
u2=new User();
u2.name=”B”;

System.out.println(u1.name);
Question: 22
class Human{
String name;
int age;
Human(String name, int age){
A. Null 0
this.name=name;
B. Adam 32000
this.age=age;
C. Error
} }
D. 32000 Adam
class Main{
public static void main(String args[]){
Human adam = new Human("Adam",32000);
System.out.println(adam.name);
System.out.println(adam.age);
} }
Question: 23
class Human{
String name;
int age; A. method foo
void foo() { method boo
this.boo(); A. method boo
System.out.println("method foo");} method boo
void boo() { A. method foo
System.out.println("method boo"); method foo
A. method boo
} }
method foo
class Main{
public static void main(String args[]){
Human adam = new Human();
adam.foo();
} }
Question: 24
class User{
String name;
void sayHello(User randomUser){
randomUser.name = "HiddenGuy";
A. HiddenGuy
randomUser=null;
B. AwesomeGuy
} }
C. AwesomeGuy HiddenGuy
public class Main{
D. Error
public static void main(String[] args) {
User u1=new User();
u1.name="Awesome Guy";
u1.sayHello(u1);
System.out.println(u1.name);
}
Question: 25
class User{
String name;
String address;
User(String x,String y){ A. X,Y
name=x; B. null
address=y; null
System.out.println(name); A. Error
System.out.println(address); B. name,address
} }
public class Main{
public static void main(String[] args) {
User u1=new User();
}
Question: 26
class Temp{
Temp() {
this(5); A. 15
System.out.println("Inside Temp"); } 5
Temp(int x) { Inside temp
this(5,15); A. 75
System.out.println(x); } 5
Temp(int x,int y) { Inside temp
System.out.println(x * y); A. Error in line number 5. No
}} method found named "this"
public class Main{ B. Inside temp
public static void main(String[] args) {
new Temp();
} }
Question: 27

class User{
String name;
void sayHello(User randomUser){ A. BadGuy
this.name = randomUser.name; BadGuy
} } A. BadGuy
public class Main{ AwesomeGuy
public static void main(String[] args) { A. AwesomeGuy
User u1=new User(); BadGuy
u1.name="Awesome Guy"; A. AwesomeGuy
User u2=new User(); AwesomeGuy
u1.name="Bad Guy";
u1.sayHello(u2);
System.out.println(u1.name);
System.out.println(u2.name);
Question: 28
class Fruit {
String name;
Fruit(String name) {
this.name = name;
} A. null Orange
} B. null null
class Main { C. Error
public static void main(String args[]) { D. Orange
Fruit orange = new Fruit("Orange");
Fruit mango = new Fruit();
System.out.println(mango.name + " " +
orange.name);
}
}
Question: 29
class User {
String name;
public User callMe(User randomUser) {
randomUser = this;
return null;
A. Random Technologies
}}
public class Main { B. Null
public static void main(String[] args) { C. Null pointer Exception
User u1 = new User(); D. Random null
u1.name = "Random";
User u2 = new User();
u2.name = "Technologies";
u2 = u1.callMe(u2);
System.out.println(u1.name + " " + u2.name);
}
}
Question: 30
class User {
int id;
void generateId(int id) {
this.id = id * 5;
}} A. 25 25
public class Main { B. 50 50
public static void main(String[] args) { C. 00
User u1 = new User(); D. 50 0
u1.generateId(5);
User u2 = u1;
u2.generateId(10);
u1 = u2;
System.out.println(u1.id + " " + u2.id);
}}
/ethnuscodemithra Ethnus Codemithra /ethnus /code_mithra

https://learn.codemithra.com

[email protected] +91 7815 095 +91 9019 921


095 340

You might also like