0% found this document useful (0 votes)
8 views

Module-2 Notes(1st IA)

The document provides an overview of object-oriented programming in Java, focusing on the concepts of classes and objects. It explains the definitions, characteristics, and examples of objects and classes, as well as the creation and initialization of objects, constructors, and the use of the 'this' keyword. Additionally, it covers static variables and methods, along with constructor overloading and the significance of instance variables.

Uploaded by

Srisaila Nath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Module-2 Notes(1st IA)

The document provides an overview of object-oriented programming in Java, focusing on the concepts of classes and objects. It explains the definitions, characteristics, and examples of objects and classes, as well as the creation and initialization of objects, constructors, and the use of the 'this' keyword. Additionally, it covers static variables and methods, along with constructor overloading and the significance of instance variables.

Uploaded by

Srisaila Nath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

21CS32 Object Oriented Programming

Module-2

INTRODUCTION TO CLASSES AND OBJECTS

We design a program using objects and classes in the object-oriented


programming technique.

An object in Java is a physical as well as a logical entity, whereas, a class in Java is


a logical entity only.

What is an object in Java?


object in Java
An entity that has a state and behavior is known as an object e.g., a chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). An
example of an intangible object is the banking system.

An object has three characteristics:

 State: represents the data (value) of an object.


 Behavior: represents an object’s behavior (functionality) such as deposit,
withdrawal, etc.
 Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM
to identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; the color is white, known as its
state. It is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which


objects are created. So, an object is the instance(result) of a class.

Object Definitions:

 An object is a real-world entity.


 An object is a runtime entity.
 The object is an entity that has a state and behavior.
 The object is an instance of a class.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 1|Page


21CS32 Object Oriented Programming
Module-2

What is a class in Java?

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. It can't be physical.

A class in Java can contain:

 Fields/ Data members


 Methods
 Constructors
 Blocks
 Nested class and interface

Syntax to declare a class:

class <class_name> {

data member/s;
method/s;}

Instance variable in Java


A variable that is created inside the class but outside the method is known as an
instance variable. The instance variable doesn't get memory at compile time. It gets
memory at runtime when an object or instance is created. That is why it is known as an
instance variable.

Method in Java
In Java, a method is like a function used to expose an object’s behavior.
Advantage of Method
 Code Reusability
 Code Optimization

new keyword in Java


The new keyword is used to allocate memory at runtime. All objects get memory
in Heap memory area.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 2|Page


21CS32 Object Oriented Programming
Module-2

Example of Class declaration


class Bike {
// Data member or field
int gear = 5;
// behavior or method
void braking() {
System.out.println("Working of Braking");
}
}

Creating an Object in Java


Here is how we can create an object of a class.

Syntax
className object = new className();
// Example for Bike class object creation
Bike sportsBike = new Bike();
Bike touringBike = new Bike();

Object and Class Example: main within the class


In this example, we created a Student class with two data members’ id and name.
We are creating the object of the Student class with a new keyword and printing the
object's value.
Here, we are creating a main() method inside the class.

//Java Program to define a class and its fields


class Student {
int id; // data member or instance variable
String name;
//creating the main method inside the Student class

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 3|Page


21CS32 Object Oriented Programming
Module-2

public static void main(String args[]){


//Creating an object or instance
Student s1=new Student();//creating an object
//Printing values of the object
System.out.println(s1.id);//accessing data members
System.out.println(s1.name);
} }
OUTPUT
0
Null
0 & Null because both the data members are not assigned
with any values except memory allocation

Object and Class Example: main outside the class


In real-time development, we create classes and use them from another class. It
is a better approach than the previous one. Let's see a simple example: we are having
the main() method in another class.
We can have multiple classes in different Java files or a single Java file. If you
define multiple classes in a single Java source file, it is a good idea to save the file name
with the class name which has the main() method.

class Student {
int id;
String name; }
// Creating another class
class TestStudent{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
} }

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 4|Page


21CS32 Object Oriented Programming
Module-2

3 Ways to initialize an object


There are 3 ways to initialize an object in Java.
 By reference variable
 By method
 By constructor

Object and Class Example: Initialization through reference


Initializing an object means storing data in the object. Let's see a simple example
where we are going to initialize the object through a reference variable.

class Student {
int id;
String name;
}
class TestStudent{
public static void main(String args[]){
Student s1=new Student();
s1.id=1;
s1.name="SrisailaNath";
//printing members with a white space
System.out.println(s1.id+" "+s1.name);
}
}
Output
1 SrisailaNath

Object and Class Example: Initialization through a method


In this example, we are creating the two objects of the Student class and initializing
the value to these objects by invoking the ReadInfo method. Here, we display the objects’
state (data) by invoking the DispInfo() method.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 5|Page


21CS32 Object Oriented Programming
Module-2

class Student{
int rollno;
String name;
void ReadInfo(int r, String n){
rollno=r;
name=n;
}
void DispInfo(){
System.out.println(rollno+" "+name);}
}
class TestStudent{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1. ReadInfo (1, "KrishnaNanda");
s2. ReadInfo (2, "NarayaniPriya");
s1. DispInfo ();
s2. DispInfo ();
} }
Output
1 KrishnaNanda
2 NarayaniPriya

Constructors in Java
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 the 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 cases, the Java
compiler provides a default constructor by default.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 6|Page


21CS32 Object Oriented Programming
Module-2

Note: It is called a 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 the java
compiler creates a default constructor if your class doesn't have any.

Rules for creating Java constructor


There are three rules defined for the constructor.
 The 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, and synchronized

Types of Java constructors


There are two types of constructors in Java:
 Default constructor (no-arg constructor)
 Parameterized constructor

Java Default Constructor


A constructor is called a "Default Constructor" when it doesn't have any parameters.

Syntax of default constructor:


<class_name>(){}
Example of default constructor

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
} }

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 7|Page


21CS32 Object Oriented Programming
Module-2

What is the purpose of a default constructor?


The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.

Example of a default constructor that displays the default values

class Student{
int id;
String name;
void display(){System.out.println(id+" "+name);}
}
class StudentTest{
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
} }
Output
0 null
0 null

In the above class, you are not creating any constructor so the compiler provides
you with a default constructor. Here 0 and null values are provided by the default
constructor.
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 8|Page


21CS32 Object Oriented Programming
Module-2

Example of parameterized constructor


In this example, we have created the constructor of the Student class that has two
parameters. We can have any number of parameters in the constructor.

class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
}
Class TestStudent{
public static void main(String args[]){
Student s1 = new Student (1, "Krishna");
Student s2 = new Student (2, "Narayani");
s1.display();
s2.display();
} }
Output
1 Krishna
2 Narayani

Constructor Overloading in Java


In Java, a constructor is just like a method but without a return type. It can also be
overloaded like Java methods.
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.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 9|Page


21CS32 Object Oriented Programming
Module-2

Example of Constructor Overloading

class Student{
int id,age;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){
System.out.println(id+" "+name+" "+age);
} }
class TestStudent{
public static void main(String args[]){
Student s1 = new Student(11,"Sri");
Student s2 = new Student(22,"Nath",25);
s1.display();
s2.display();
} }
Output
11 Sri
12 Nath 25

Static keyword in Java


The static keyword in Java is used for memory management mainly. We can apply
static keywords with variables, methods, and blocks. The static keyword belongs to the
class than an instance of the class.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 10 | P a g e


21CS32 Object Oriented Programming
Module-2

The static can be:


 Variable (also known as a class variable)
 Method (also known as a class method)
 Block
Java static variable
If you declare any variable as static, it is known as a static variable.

The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of employees, the
college name of students, etc.
The static variable gets memory only once in the class area at the time of class
loading.

class Countstatic{
int count=0;
static int cnt=0; //will get memory only once
Countstatic(){
count++;
cnt++;
System.out.println("Normal Counter\t"+count);
System.out.println("Static counter\t"+cnt);
}
public static void main(String args[]){
//creating objects
Countstatic c1=new Countstatic();
Countstatic c2=new Countstatic();
Countstatic c3=new Countstatic();
} } Output
Normal Counter 1 Static Counter 1
Normal Counter 1 Static Counter 2
Normal Counter 1 Static Counter 3

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 11 | P a g e


21CS32 Object Oriented Programming
Module-2

Java static method


If you apply a static keyword with any method, it is known as a static method.

 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data members and can change their value.

class demoStatic{
// Static method
static void disp(){
System.out.println("disp block in demo");
}}
class testStatic{
public static void main(String arg[]){
demoStatic.disp(); //calling static method
System.out.println("Main Method");
}
//static block 1
static{
System.out.println("Static block1 in Test");
}
// static block 2
static{
System.out.println("Static block2 in Test ");
} }
Output
Static block1 in Test
Static block2 in Test
disp block in demo
Main Method

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 12 | P a g e


21CS32 Object Oriented Programming
Module-2

this keyword in Java


There can be a lot of usage of Java this keyword. 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.

Note: If you are beginner to java, lookup only three usages of this keyword.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 13 | P a g e


21CS32 Object Oriented Programming
Module-2

this: to refer to the current class instance variable


this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.

Let’s Understanding the problem without this keyword


class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){
System.out.println(rollno+"\t "+name+"\t "+fee);
} }
class TestThis{
public static void main(String args[]){
Student s1=new Student(21,"Joshi ",5000);
Student s2=new Student(55,"Gagan",6000);
s1.display();
s2.display();
}}
Output
0 null 0
0 null 0

In the above example, parameters (formal arguments) and instance variables are the
same. Hence creating an ambiguous state, and are not able to assign the values to instance
variables. To avoid such an ambiguous state this keyword is used as shown below.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 14 | P a g e


21CS32 Object Oriented Programming
Module-2

Example Program using this keyword to resolve ambiguous state

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){
System.out.println(rollno+"\t "+name+"\t "+fee);
} }
class TestThis{
public static void main(String args[]){
Student s1=new Student(2,"Aiyan ",5000);
Student s2=new Student(3,"Padminin",6000);
s1.display();
s2.display();
}}
Output
2 Aiyan 5000
3 Padmini 6000

this: to invoke the current class method


You may invoke the method of the current class by using this keyword. If you don't
use this keyword, the compiler automatically adds this keyword while invoking the
method. Let's have an example with a diagrammatic representation.

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 15 | P a g e


21CS32 Object Oriented Programming
Module-2

Example Program to represent how this keyword is used in invoking methods of a class

import java.util.*;
class ThisMethod {
String name;
void setName(String name) {
this.name = name; }
String getName() {
return name; }
void disp() {
System.out.println("Student Name is: "+this.getName());
}}
class ThisMethodTest{
public static void main(String args[]) {
ThisMethod obj = new ThisMethod();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
obj.setName(name);
obj.disp();
}} Output
Enter the name of the student – Adithya Barade
Student Name is – Adithya Barade

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 16 | P a g e


21CS32 Object Oriented Programming
Module-2

this(): to invoke the current class constructor


this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor.
Example Program to represent how this() can be used to invoke a constructor

class A{
A() {
System.out.println("Default Constructor");
}
A(String name){
this();
System.out.println(name);
}}
class B{
public static void main(String arg[]){
A oba=new A("Hello");
A oba1=new A("HI");
}}
Output
Default Constructor
Hello
Default Constructor
Hi

**** First IA Syllabus ****

Prepared by: SrisailaNath Asst. Prof. Dept. of CSE 17 | P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy