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

U2 Class Introduction_CAG

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, emphasizing the importance of classes as templates for creating objects that encapsulate data and behavior. It explains key concepts such as data abstraction, instance creation, member variables, and methods, along with visibility controls in Java. The document includes examples of class definitions, object instantiation, and method usage to illustrate these concepts.

Uploaded by

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

U2 Class Introduction_CAG

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, emphasizing the importance of classes as templates for creating objects that encapsulate data and behavior. It explains key concepts such as data abstraction, instance creation, member variables, and methods, along with visibility controls in Java. The document includes examples of class definitions, object instantiation, and method usage to illustrate these concepts.

Uploaded by

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

UNIT-II

OBJECT ORIENTED
PROGRAMMING CONEPTS

Prepared By:
C A Gajjar
Lecturer in IT
Dr. S & S S Ghandhy College Of Engg. & Tech., Surat

1
Introduction
 Java is a true OO language and therefore the underlying structure
of all Java programs is classes.
 Anything we wish to represent in Java must be encapsulated in a
class that defines the “state” and “behaviour” of the basic
program components known as objects.
 Classes create objects and objects use methods to communicate
between them. They provide a convenient method for packaging
a group of logically related data items and functions that work
on them.
 A class essentially serves as a template for an object and behaves
like a basic data type “int”.
 It is therefore important to understand how the fields and
methods are defined in a class and how they are used to build a
Java program that incorporates the basic OO concepts such as
encapsulation, inheritance, and polymorphism.

2
Classes
 A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
 A Class is a 3-Compartment Box Encapsulating Data and Operations

 Name (or identity): identifies the class.


 Variables (or attribute, state, field): contains the static attributes of the
class.
 Methods (or behaviors, function, operation): contains the dynamic
behaviors of the class.
 a class encapsulates the static attributes (data) and dynamic behaviors
(operations that operate on the data) in a box. 3
Classes
 Defines a new data type.
 Template for an object, and an object is an
instance of a class.

Box

width
height
depth

volume()

4
5
Class Definition in Java
 The general form for a class definition:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

Return-type methodname1(parameter-list) {
// body of method
}
Return-type methodname2(parameter-list) {
// body of method
}
// ...
Return-type methodnameN(parameter-list) {
// body of method
}
}

6
A Simple Class
 Class with no methods

class Box {
double width;
double height;
double depth;
}

7
A Simple Class
 Class with methods

class Box {
double width;
double height; Instance Variable
double depth;
void volume(){
//Run method implementation Instance Method

}
}

8
A Simple Class
Declaration of Instance variable:
 Variables defined within a class are called
instance variables because each instance of class
contains its own copy of these variables.
 Ex.Width, Height and depth

Declaration of Method:-
 Methods defined with in a class are called
instance methods.
 Ex. volume()

9
A Simple Class
public class Circle { // class name
double radius; // variables
String color;
double getRadius() { ...... } // methods
double getArea() { ...... }
}

public class SoccerPlayer { // class name


int number; // variables
String name;
int x, y;
void run() { ...... } // methods
void kickBall() { ...... }
}

10
Data Abstraction
 Declare the Box class, have created a new data
type – Data Abstraction

 Can define variables (objects) of that type:

Box aBox;
Box bBox;

11
Class of Box
 aBox, bBox simply refers to a Box object, not an
object itself.

aBox bBox

null null

Points to nothing (Null Reference) Points to nothing (Null Reference)

12
Creating objects/Instance of a class
 To create an instance/object of a class, you have to:
 Declare an instance identifier (instance name) of a
particular class.
 Construct the instance (i.e., allocate storage for the
instance and initialize the instance) using the "new"
operator.
 Objects/Instances are created dynamically using the
new keyword.

13
Creating objects/Instance of a class
 aBox and bBox refer to Box objects.

aBox = new Box() ; bBox = new Box() ;

14
Creating objects/Instance of a class
aBox = new Box();
bBox = new Box() ;

bBox = aBox;

Before Assignment After Assignment

aBox bBox aBox bBox

15
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.

16
Creating objects/Instance of a class
// Declare 3 instances of the class Circle, c1, c2, and c3

Circle c1, c2, c3;


// They hold a special value called null

// Construct the instances via new operator

c1 = new Circle();
c2 = new Circle(2.0);
c3 = new Circle(3.0, "red");
// You can Declare and Construct in the same statement

Circle c4 = new Circle();

17
Object creation
 To create c1 object of Circle class, we can write:
Circle c1 = new Circle();
 Here, new is an operator that creates the object of Circle class.
 Here, left hand side is Circle is the class name and c1 is object
name. c1 is actually a variable of Circle class.
 This variable stores reference number of object returned by JVM,
after creating the object.
 Here, c1 is a variable and Circle is class name as well as data
type of c1.
 We can say that c1 is a variable of Circle class type.

18
Object creation
 When an object is created, the memory is allocated on ‘heap’.
 After creation of an object, JVM produces a unique reference
number for the object from the memory address of the object.
 This reference number is also classed hash code number.
 To know hash code number (or reference) of an object, we can
use hashcode()method of Object class.
class Circle{
int radius;
String color;
void getRadius(){}
void getArea(){}
}
class Demo{
public static void main(String args[]){
Circle c1 = new Circle();
System.out.println("Hash code="+c1.hashCode());
}
}
19
Hash code=798154996
Memory organization for members of a class

ptr to special
ptr to Heap structure ptr to static variables
object reference Instance variable ptr to method1
Instance variable ptr to method2
special structure

code method2
heap memory static
code method1 variables

method area

20
Dot (.) Operator
 The variables and methods of a class are formally
called member variables and member methods.
 To reference a member variable or method, you must:
 First identify the instance you are interested in, and then,
 Use the dot operator (.) to reference the desired member variable
or method.
 For example,
 In a class Circle, with two member variables (radius and color) and
two member methods (getRadius() and getArea()).
 We have created three instances of the class Circle,
namely, c1, c2 and c3.
 To invoke the method getArea(), you must first identity the
instance of interest, says c2, then use the dot operator, in the form
of c2.getArea().
21
Dot (.) Operator
// Suppose that the class Circle has variables radius and color,
// and methods getArea() and getRadius().
// Declare and construct instances c1 and c2 of the class Circle

Circle c1 = new Circle ();


Circle c2 = new Circle ();
// Invoke member methods for the instance c1 via dot operator

System.out.println(c1.getArea());
System.out.println(c1.getRadius());
// Reference member variables for instance c2 via dot operator

c2.radius = 5.0;
c2.color = "blue";
22
Member Variables
 A member variable has a name (or identifier) and a type;
and holds a value of that particular type.
 Variable Naming Convention: A variable name shall be a
noun or a noun phrase made up of several words. The first
word is in lowercase and the rest of the words are initial-
capitalized (camel-case),
e.g., fontSize, roomNumber, xMax, yMin and xTopLeft.
 The formal syntax for variable definition in Java is:
 [AccessControlModifier] type variableName [= initialValue];
[AccessControlModifier] type variableName-1 [= initialValue-1] [, type
variableName-2 [= initialValue-2]] ... ;
 For example,
private double radius;
public int length = 1, width = 1;
23
Member Methods
 A method:
1.receives arguments from the caller,
2.performs the operations defined in the method body,
and
3.returns a piece of result (or void) to the caller.
 The syntax for method declaration in Java is as
follows:
 [AccessControlModifier] returnType methodName
([parameterList]) { // method body or implementation ...... }
 For examples:
 // Return the area of this Circle instance
public double getArea() { return radius * radius * Math.PI; }
24
Member Methods
 Method Naming Convention:
 A method name shall be a verb, or a verb phrase
made up of several words.
 The first word is in lowercase and the rest of the
words are initial-capitalized (camel-case).
 For example,
getArea(), setRadius(), getParameterValues(), hasNext().
 A variable name is a noun, denoting an attribute;
 A method name is a verb, denoting an action.
 A class name is a noun beginning with
uppercase.
25
Example
class Box{
double width;
double height;
double depth;
}
class BoxDemo{
public static void main(String[] args) {
Box mybox = new Box();
double vol;
//Assign values to mybox instance variable
mybox.width = 10;
mybox.height = 20;
mybox.width = 5;
//Compute volume of object mybox
vol = mybox.width * mybox.height * mybox.width;
System.out.println("Volume is ="+vol);
}
}

26
Adding a Method to the Box Class
// This program includes a method inside the box class.
class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is =");
System.out.println(width * height * depth);
}
}

27
Adding a Method to the Box Class
class Box {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// assign different values to mybox2's instance variables
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
28
Method that Takes Parameters
//sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
//in main program method can be called to set box
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
//initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
29
Circle Class
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;
} Method Body
public double area() {
return 3.14 * r * r;
}
}

30
Circle Program
public class Circle {
public double x, y;
public double r;
public double circumference() {return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
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 AR = aCircle.area(); // invoking method
double Circum = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+AR);
System.out.println("Circumference ="+Circum);
}
}
31
Better way of Initialising or Access Data
Members x, y, r
 When there too many items to update/access and also to
develop a readable code, generally it is done by defining
specific method for each purpose.
 To initialise/Update a value:
 aCircle.setX( 10 )
 To access a value:
 aCircle.getX()
 These methods are informally called as Accessors or
Setters/Getters Methods.

32
Accessors – “Getters/Setters”

public class Circle {


private double x,y,r;

//Methods to return circumference and area


public double getX() { return x;}
public double getY() { return y;}
public double getR() { return r;}
public double setX(double x_in) { x = x_in;}
public double serY(double y_in) { y = y_in;}
public double setR(double r_in) { r = r_in;}

33
How does this code looks ? More
readable ?
// 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.setX(10);
aCircle.setY(20);
aCircle.setR(5);
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.getR()+" Area="+area);
System.out.println("Radius="+aCircle.getR()+" Circumference
="+circumf);
}
}

34
Visibility Controls/Access Modifiers of JAVA

 Java provides a number of access modifiers to set


access levels for classes, variables, methods and
constructors.
 The four access levels are:
 Package/friendly (default) -Visible to the package.
No modifiers are needed.
 Private - Visible to the class only.
 Public- Visible to the class as well as outside the
class.
 Protected- Visible to the package and all sub
Classes.
36
Visibility Controls/Access Modifiers of JAVA

37
Visibility Controls of JAVA
Default Access Modifier – No Keyword
 Default access modifier means no need to declare an access
modifier for a class, field, method etc.
 A variable or method declared without any access control
modifier is available to any other class in the same
package.
 The default modifier cannot be used for methods in an
interface because the methods in an interface are by default
public.

38
Visibility Controls of JAVA
Default Access Modifier – Example
class BaseClass
{ BaseClass::Display with
'default' scope
void display()
{
System.out.println("BaseClass::Display with 'default' scope");
}
}
class Main
{
public static void main(String[] args) {
//access class with default scope
BaseClass obj = new BaseClass();

obj.display(); //access class method with default scope


}
}

39
Visibility Controls of JAVA
Public Access Modifier - public
 The public keyword is an access specifier, which allows the
programmer to control the visibility of class members.
 When a class member is preceded by public, then that
member may be accessed by code outside the class.
 A class, method, constructor, interface etc declared public can
be accessed from any other class.
 Therefore, methods or blocks declared inside a public class
can be accessed from any class belonging to the Java world.
 However, if the public class we are trying to access is in a
different package, and then the public class still need to be
imported. Because of class inheritance, all public methods
and variables of a class are inherited by its subClasses.

40
Visibility Controls of JAVA
Public Access Modifier - public
 Example:
public static void main(String[] args)
{
// ...
}
 The main( ) method of an application needs to be public.

Otherwise, it could not be called by a Java interpreter (such as


java) to run the class.

41
Visibility Controls of JAVA
Public Access Modifier – Example
class Test
{
public void display()
{
System.out.println("Software Testing");
}
}
class Main
{
public static void main(String[] args)
{
Test obj = new Test();
obj.display();
}
}

42
Visibility Controls of JAVA
Protected Access Modifier – Protected
 Variables, methods and constructors which are declared
protected in a super class can be accessed only by the
subClasses in other package or any class within the package
of the protected members' class.
 The protected access modifier cannot be applied to class and
interfaces.
 Methods can be declared protected, however methods in a
interface cannot be declared protected.
 Protected access gives chance to the subClass to use the
helper method or variable, while prevents a non-related class
from trying to use it.

43
Visibility Controls of JAVA
Protected Access Modifier – Protected

44
Visibility Controls of JAVA
Private Access Modifier – private
 Methods, Variables and Constructors that are
declared private can only be accessed within the
declared class itself.
 Private access modifier is the most restrictive
access level. Class and interfaces cannot be
private.
 Variables that are declared private can be accessed

outside the class if public getter methods are


present in the class.
 Using the private modifier, an object encapsulates
itself and hides data from the outside world.
46
Visibility Controls of JAVA
Private Access Modifier – private
 Private access modifier cannot be used for classes

and interfaces.
 The scope of private entities (methods and variables)

is limited to the class in which they are declared.


 A class with a private constructor cannot create an

object of the class from any other place like the main
method.

47
Visibility Controls of JAVA
Private Access Modifier – Example

48
Visibility Controls of JAVA
Private Access Modifier – private
Example:
class A {
private String s1 = "Hello";
public String getName() {
return this.s1;}
}
 Here, s1 variable of A class is private, so there's no

way for other classes to retrieve.


 So, to make this variable available to the outside

world, we defined public methods: getName(), which


returns the value of s1. 49
Private Access Specifier Example
class Rectangle{
private double length;
private double breadth;

void findArea(){
double area;
area = length * breadth;
System.out.println("Area = "+area);
}
}
class PrivateClass{
public static void main(String args[]){
Rectangle R = new Rectangle();
R.length = 10;
R.breadth = 5;
R.findArea();
}
} 50
Private Access Specifier Example
Output:

PrivateClass.java:16: error: length has private access in Rectangle


R.length = 10;
^
PrivateClass.java:17: error: breadth has private access in Rectangle
R.breadth = 5;
^
2 errors

51
this Keyword
 Sometimes a method will need to refer to the object that invoked
it.
 To allow this, Java defines the this keyword. Keyword this can
be used inside any method or constructor of class to refer to the
current object.
 It means, this is always a reference to the object on which the
method was invoked.
 this keyword can be very useful in case of Variable Hiding.
 We cannot create two Instance/Local variables with same name.
But it is legal to create one instance variable & one local variable
or method parameter with same name.
 Local Variable will hide the instance variable which is called
Variable Hiding.

52
this Keyword

53
this Keyword
 this: to refer current class instance variable
The 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.
 this: to invoke current class method
You may invoke the method of the current class by using the this
keyword.
 this: to reuse constructor call
The this() constructor call should be used to reuse the constructor
from the constructor.
It maintains the chain between the constructors i.e. it is used for
constructor chaining.

54
this: to refer current class instance variable
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+" "+name+" "+fee);
}
}
class Test{
public static void main(String[] args) {
Student s1 = new Student(11,"Ankit",5000f);
Student s2 = new Student(22,"Sameer",5500f);
s1.display();
s2.display();
111 Ankit 5000.0
}
112 Sameer 5500.0
} 55
this: to invoke current class method
class Sample{
void methodOne(){
System.out.println("Inside methodOne");
}
void methodTwo(){
System.out.println("Inside methodTwo");
this.methodOne(); //same as methodOne();
}
}
class TestThis{
public static void main(String[] args) {
Sample obj = new Sample();
obj.methodTwo();
}
}

Inside methodTwo
Inside methodOne
56
this: to reuse constructor call
class Student{
int rollno; 111 ankit java 0.0
String name, course; 112 sumit java 6000.0
float fee;
Student(int rollno, String name, String course){
this.rollno = rollno;
this.name = name;
this.course = course;
}
Student(int rollno, String name, String course, float fee){
this(rollno, name, course); //reusing constructor
this.fee = fee;
}
void display(){
System.out.println(rollno+" "+name+" "+course+" "+fee);
}
}
class Test1{
public static void main(String[] args) {
Student s1 = new Student(11,"Ankit","Java");
Student s2 = new Student(22,"Sameer","Python",5500f);
s1.display();
s2.display();
}
} 57
Static Keyword
 The static keyword in Java is used for memory
management mainly.
 We can apply static keyword with variables,
methods, blocks and nested classes.
 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)

 Block

 Nested class

58
Static Keyword
Static Variable:-
 If we 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, college name of students, etc.
 The static variable gets memory only once in the

class area at the time of class loading.


Advantages of static variable:-
 It makes your program memory efficient (i.e., it saves

memory).
59
Static Keyword
class Student{
int rollno;
String name;
static String college=“SSGC"; }
 Suppose there are 500 students in my college, now all
instance data members will get memory each time when the
object is created.
 All students have its unique rollno and name, so instance data
member is good in such case.
 Here, "college" refers to the common property of all objects.
 If we make it static, this field will get the memory only once.
 Java static property is shared to all objects.

60
Static Keyword
class Student{
int rollno; 11 Karan SSGC
String name; 22 Sumit SSGC
static String college = "SSGC";
Student(int r,String n){
rollno = r;
name = n;
}
void display(){
System.out.println(rollno+" "+name+" "+college);
}
}
class Test2{
public static void main(String[] args) {
Student s1 = new Student(11,"Karan");
Student s2 = new Student(22,"Sumit");
s1.display();
s2.display();
}
}
//we can change the college of all objects by the single line of code
//Student.college=“DrSSGCSurat" 61
Static Keyword
 Program of the counter without static variable:-
//Use of instance variable which get memory
//each time when we create object of a class.
class Counter{
int cnt = 0; //will get memory each time when object is created

Counter(){
cnt ++;
System.out.println("Count="+cnt);
}
}
class Test3{
public static void main(String[] args) {
//Creating objects
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
} Count=1
} Count=1
Count=1

62
Static Keyword
 Program of counter by static variable
//Use of static variable which
//is shared with all the objects of a class.
class CounterTwo{
static int cnt = 0; //will get memory only once and retain value
CounterTwo(){
cnt ++;
System.out.println("Count="+cnt);
}
}
class Test3{
public static void main(String[] args) {
//Creating objects
CounterTwo c1 = new CounterTwo();
CounterTwo c2 = new CounterTwo();
CounterTwo c3 = new CounterTwo();
}
Count=1
}
Count=2
Count=3

63
Static Keyword
Static Variable Non- Static Variable
Static variables can be accessed using Non static variables can be accessed
class name. using instance of a class.
Syntax Syntax
class_name.variable_name obj_ref.variable_name
Static variables can be accessed by Non static variables cannot be
static and non static methods accessed inside a static method.
Static variables reduce the amount of Non static variables do not reduce the
memory used by a program. amount of memory used by a program
Static variables are shared among all Non static variables are specific to that
instances of a class. instance of a class.
Static variable is like a global variable Non static variable is like a local
and is available to all methods. variable and they can be accessed
through only instance of a class.
Memory is allocated at the time of Non-static variable also known as
loading of class so that these are also instance variable while because
known as class variable. memory is allocated whenever
instance is created. 64
Static Keyword
Java static method:-
 If you apply static keyword with any method, it is
known as 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 member and
can change the value of it.

65
Static Keyword
class Student{
int rollno;
String name;
static String college = "SSGC";
static void change(){ //static method
college = "DrSSGCSurat";
}
Student(int r, String n){
rollno = r;
name = n;
}
void display(){
System.out.println(rollno+" "+name+" "+college);
}
}
class TestStatic{
public static void main(String[] args) {
Student.change(); //static method call: Class.Method();
Student s1 = new Student(11, "Rahul");
11 Rahul DrSSGCSurat
Student s2 = new Student(12, "Ronak");
Student s3 = new Student(22, "Rakesh"); 12 Ronak DrSSGCSurat
s1.display(); 22 Rakesh DrSSGCSurat
s2.display();
s3.display();
}
}
66
Static Keyword
class Calculate{
static int cube(int n){
return n*n*n;
}

public static void main(String[] args){


int result = Calculate.cube(5);
System.out.print("Cube ="+result);
}
}

67
Static Keyword
Static Method Non- Static Method
These method always preceded by These method never be preceded by
static keyword. static keyword
Syntax Syntax
static void fun2() void fun2()
{....} {....}
Memory is allocated only once at the Memory is allocated multiple time
time of class loading. whenever method is calling.
These are common to every object so It is specific to an object so that these
that it is also known as member are also known as instance method.
method or class method.
These property always access with These methods always access with
class reference object reference
Syntax: Syntax:
className.methodname(); Objref.methodname();
If any method wants to be execute only If any method wants to be execute
once in the program that can be multiple time that can be declare as
declare as static . non static. 69
Static Keyword
Restrictions for the static method :-
 There are two main restrictions for the static

method.
 The static method can not use non static data

member or call non-static method directly.


 this and super cannot be used in static context.

Why is the Java main method static?


 It is because the object is not required to call a static
method.
 If it were a non-static method, JVM creates an object
first then call main() method that will lead the
problem of extra memory allocation.
70
Static Keyword
Java static block :-
 It is used to initialize the static data member.

 It is executed before the main method at the

time of class loading.


class StaticBlock{
static{
System.out.println("Static Block is executed");
}
public static void main(String[] args) {
System.out.print("main method executed");
}
}
Static block is executed
main method executed
71
Static Keyword
Static block executes before the main method:-
 A Class has to be loaded in main memory
before we start using it.
 Static block is executed during class loading.
 This is the reason why static block executes
before the main method.

72
Static Keyword
class Main{
static int a = 23;
static int b;
static int max;

//static blocks
static{
System.out.println("First Static Block");
b = a * 4;
}
static {
System.out.println("Second Static Block");
max = 30;
} First Static block.
//static method Second Static block.
static void display(){ a = 23
System.out.println("a = "+a); b = 92
System.out.println("b = "+b); Max = 30
System.out.println("Max = "+max);
}
public static void main(String[] args) {
display();
}
} 73
Method Overloading
 If class have multiple methods with same name but different
parameters is known as Method Overloading.
 Method overloading is also known as compile time (static)
polymorphism.
 The same method name will be used with different number of
parameters and parameters of different type.
 Overloading of methods with different return types is not allowed.
 Compiler identifies which method should be called among all the
methods have same name using the type and number of arguments.
 However, the two functions with the same name must differ in at
least one of the following,
 The number of parameters
 The data type of parameters
 The order of parameter

74
Method Overloading

Sum of (a+b) is:: 20


Sum of (a+b+c) is:: 30
Sum of double (a+b) is:: 21.0

75
Constructors
 Constructor is a special method that gets invoked
“automatically” at the time of object creation.
 Constructor is normally used for initializing
objects with default values unless different
values are supplied.
 Constructor has the same name as the class
name.
 Constructor cannot return values.
 A class can have more than one constructor as
long as they have different signature (i.e.,
different input arguments syntax).
76
Constructors
 A constructor is different from an ordinary method
in the following aspects:
 The name of the constructor method is the same as the
class name.
 Constructor has no return type. It implicitly
returns void. No return statement is allowed inside the
constructor's body.
 Constructor can only be invoked via the "new"
operator. It can only be used once to initialize the
instance constructed. Once an instance is constructed,
you cannot call the constructor anymore.
 Constructors are not inherited
77
Constructors
 Types of Constructors:
 Default Constructor
 Parameterized Constructor
 Copy Constructor
 Private Constructor

78
Constructors
 Default Constructor:
 A constructor with no parameter is called the default
constructor.
 It initializes the member variables to their default
value.
 For example,
 Circle() constructor initialize member
variables radius and color to their default value.

79
Defining a Constructor
 Like any other method
public class ClassName {

// Data Fields…

// Constructor
public ClassName()
{
// Method Body Statements initialising Data
Fields
}

//Methods to manipulate data fields


}

 Invoking:
 There is NO explicit invocation statement needed:
When the object creation statement is executed, the
constructor method will be executed automatically.
80
Defining a Constructor: Example

81
82
83
Parameterized Constructors
 A constructor that has parameters is known as
parameterized constructor.
 It is used to provide different values to the
distinct objects.
 It is required to pass parameters on creation of
objects.
 If we define only parameterized constructors,
then we cannot create an object with default
constructor.
 This is because compiler will not create default
constructor. You need to create default
constructor explicitly.
90
111 Karan 222 Aryan

Parameterized Constructors

111 Karan
222 Aryan

91
111 Karan 222 Aryan

Parameterized Constructors

Default constructor called


parametreised constructor called
salary is :6500.0

92
Parameterized Constructors

93
Parameterized Constructors

94
111 Karan 222 Aryan

Copy Constructors
 A copy constructor is a constructor that takes only
one parameter which is the same type as the class in
which the copy constructor is defined.
 A copy constructor is used to create another object
that is a copy of the object that it takes as a
parameter. But, the newly created copy is totally
independent of the original object.
 It is independent in the sense that the copy is located
at different address in memory than the original.

96
111 Karan 222 Aryan

Copy Constructors

10xyz
20abc
10xyz

97
111 Karan 222 Aryan

Copy Constructors
Advantages of copy constructor:
 The Copy constructor is easier to use when
our class contains a complex object with
several parameters.
 Whenever we want to add any field to our
class, then we can do so just by changing the
input to the constructor.
 One of the most crucial importance of copy
constructors is that there is no need for any
typecasting.

98
111 Karan 222 Aryan

Private Constructors
 Java allows us to declare a constructor as
private.
 We can declare a constructor private by using
the private access specifier.
 Note that if a constructor is declared private,
we are not able to create an object of the class.
 we can use this private constructor in
Singleton Design Pattern.
 i.e. a class must ensure that only single instance
should be created and single object can be used
by all other classes.
99
111 Karan 222 Aryan

Rules for Private Constructors


 It does not allow a class to be sub-classed.
 It does not allow to create an object outside the class.
 If a class has a private constructor and when we try to extend
the class, a compile-time error occurs.
 We cannot access a private constructor from any other class.
 If all the constant methods are there in our class, we can use
a private constructor.
 If all the methods are static then we can use a private
constructor.
 We can use a public function to call the private constructor if
an object is not initialized.
 We can return only the instance of that object if an object is
already initialized. 10
0
Private Constructors

10
2
111 Karan 222 Aryan

Private Constructors

10
3
111 Karan 222 Aryan

Constructor Overloading
 Constructor overloading in java allows to
more than one constructor inside one Class.
 It is not much different than method
overloading.
 In Constructor overloading you have multiple
constructors with different signature with
only difference that constructor doesn't have
return type.
 These types of constructor known as
overloaded constructor.

105
111 Karan 222 Aryan

Constructor Overloading
/* programe defines three constructors to initialize the dimensions of a
box various ways using constructor overloading. */
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Box() { // constructor used when no dimensions specified
width = -1; // use -1 to indicate
height= -1; // an uninitialized
depth = -1; // box
}
Box(double len) { // constructor used when cube is created
width = height = depth = len;
}
double volume() { // compute and return volume
return width * height * depth;
}
}
106
111 Karan 222 Aryan

Constructor Overloading
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0 107
111 Karan 222 Aryan

Constructor Overloading

108
111 Karan 222 Aryan

Constructor Overloading

Default constructor calledsalary is :0.0


parametreised constructor calledsalary is :6500.0
salary is :10000.0

109
String Class:-
111 Karan 222 Aryan

 Strings are widely used in JAVA Programming, are not


only a sequence of characters but it defines object.
 String Class is defined in package.
 The String type is used to declare string variables. Also
we can declare array of strings.
 A variable of type String can be assign to another
variable of type String.
 It is class
 Due to Final, String class cannot be inherited.
 It is immutable.

110
String Class:-
111 Karan 222 Aryan

 Creating a String:-
 String literal :-

 To make Java more memory efficient. (because no new


objects are created if it exists already in the string
constant pool).

//It doesn't create a new instance

111
String Class:-
111 Karan 222 Aryan

 Creating a String:-
 Using new keyword :-

 JVM will create a new string object in normal (non-


pool) heap memory, and the literal “Ghandhy College"
will be placed in the string constant pool.
 The variable will refer to the object in a heap (non-
pool).
 //it will
create two objects and one reference variable

112
Methods/Operations of String Class
Method Description
length () Returns the length of this string.
toUpperCase() Converts all of the characters in this String to upper
case.
toLowerCase() Converts all of the characters in this String to lower
case.
substring(): extracts a substring from the string and returns it.

charAt(int index) Returns the char value at the specified index.

compareTo(String Compares two strings lexicographically.


anotherString)
equals(Object anObject) Compares this string to the specified object.
contains(): method checks whether the specified string
(sequence of characters) is present in the string or
not
split(String regex) Splits this string around matches of the given regular
expression.

113
String Class:-
111 Karan 222 Aryan

 Length():To get the length of the string

114
String Class:-
111 Karan 222 Aryan

 toUpperCase():Converts all of the characters in this String


to upper case.
 toLowerCase():Converts all of the characters in this String
to lower case.

115
String Class:-
111 Karan 222 Aryan

 substring():extracts a substring from the string and


returns it.
Syntax :
 string. Substring(int startIndex, int endIndex)

Here, string is an object of the String class.


1. startIndex - the beginning index
2. endIndex (optional) - the ending index
 The substring begins with the character at the startIndex

and extends to the character at index endIndex - 1.


 If the endIndex is not passed, the substring begins with the
character at the specified index and extends to the end of the
string.

116
String Class:-
111 Karan 222 Aryan

117
String Class:-
111 Karan 222 Aryan

118
String Class:-
111 Karan 222 Aryan

 charAt():method returns the character at the specified


index.
Syntax:
 string.charAt(int index)

Here, string is an object of the String class.


 charAt() Parameters:

index - the index of the character (an int value)


 charAt() Return Value:

It returns the character at the specified index

119
String Class:-
111 Karan 222 Aryan

120
String Class:-
111 Karan 222 Aryan

 Java String compare:-


There are three ways to compare String in Java:
1. By Using equals() Method
2. By Using == Operator
3. By compareTo() Method

121
String Class:-
111 Karan 222 Aryan

 equals():The equals() method returns true if two strings


are equal. If not, it returns false.
 Syntax: string.equals(String str)
Here, string is an object of the String class.
 equals() Parameters:-
The equals() method takes a single parameter.
str - the string to be compared
 equals() Return Value:-
returns true if the strings are equal
returns false if the strings are not equal
returns false if the str argument is null
122
String Class:-
111 Karan 222 Aryan

123
String Class:-
111 Karan 222 Aryan

 By Using == operator
 The == operator compares references not values.

124
String Class:-
111 Karan 222 Aryan

 By Using compareTo() method:-


The String class compareTo() method compares values
lexicographically and returns an integer value that
describes if first string is less than, equal to or greater
than second string.
 Syntax: string.compareTo(String str)
Suppose s1 and s2 are two String objects. If:
s1 == s2 : The method returns 0.
s1 > s2 : The method returns a positive value.
s1 < s2 : The method returns a negative value.

125
String Class:-
111 Karan 222 Aryan

class StringCompare{
public static void main(String[] args) {
String s1 = "Rohan";
String s2 = "Rohan";
String s3 = "Sohan";

System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //-1
System.out.println(s3.compareTo(s1)); //1
}
}

126
String Class:-
111 Karan 222 Aryan

 contains(): This method checks whether the specified


string (sequence of characters) is present in the string or
not.
 Syntax: string.contains(CharSequence ch)
Here, string is an object of the String class.
 contains() Parameters:
The contains() method takes a single parameter.
ch (charSequence) - a sequence of characters
 Note: A charSequence is a sequence of characters such as: String,
CharBuffer, StringBuffer etc.
returns true if the string contains the specified character
returns false if the string doesn't contain the specified character
127
String Class:-
111 Karan 222 Aryan

128
String Class:-
111 Karan 222 Aryan

 split():method divides the string at the specified regex


and returns an array of substrings.
 Syntax: string.split(String regex, int limit)

The string split() method can take two parameters:


1.regex - the string is divided at this regex (can be
strings)
2.limit (optional) - controls the number of resulting
substrings
If the limit parameter is not passed, split() returns all
possible substrings.
 split() Return Value: returns an array of substrings

129
String Class:-
111 Karan 222 Aryan

130
StringBuffer Class:-
111 Karan 222 Aryan

 Java StringBuffer class is used to create mutable


(modifiable) String objects.
 The StringBuffer class in Java is the same as String
class except it is mutable. i.e. it can be changed.
 Java StringBuffer class is a thread-safe, mutable
sequence of characters.
 Every string buffer has a capacity.
 It contains some particular sequence of characters, but
the length and content of the sequence can be changed
through certain method calls.
 StringBuffer defines 4 constructors.

131
StringBuffer Class:-
111 Karan 222 Aryan

Constructor Description
StringBuffer() This constructs a string buffer with no
characters in it and an initial capacity of 16
characters.

StringBuffer(CharSequ This constructs a string buffer that contains the


enceseq) same characters as the specified
CharSequence.

StringBuffer(int This constructs a string buffer with no


capacity) characters in it and the specified initial
capacity.

StringBuffer(String str) This constructs a string buffer initialized to


the contents of the specified string.

132
StringBuffer Class:-
111 Karan 222 Aryan

133
StringBuffer Class:-
111 Karan 222 Aryan

 Methods of StringBuffer Class:


Method Description
Inserts the string representation of the char
insert(int offset, char c)
argument into this character sequence.

append(String str) Appends the string to this character sequence.

The character sequence contained in this string


reverse()
buffer is replaced by the reverse of the sequence.

Returns the current capacity of the String


capacity()
buffer.

This method returns the char value in this


charAt(int index)
sequenceatthespecifiedindex.

This method returns a string representing the


toString()
data in this sequence.
134
StringBuffer Class:-
111 Karan 222 Aryan

 append():-This method will concatenate the string representation


of any type of data to the end of the StringBuffer object.
 append() method has several overloaded forms.
 StringBuffer append(String str)
 StringBuffer append(int n)
 StringBuffer append(Object obj)

Output: test123

135
StringBuffer Class:-
111 Karan 222 Aryan

 insert():method inserts one string into another. Here are few


forms of insert() method.
 StringBuffer insert(int index, String str)
 StringBuffer insert(int index, int num)
 StringBuffer insert(int index, Object obj)
 Here the first parameter gives the index at which position the
string will be inserted and string representation of second
parameter is inserted into StringBuffer object.

Output: te123st

136
StringBuffer Class:-
111 Karan 222 Aryan

 reverse(): method reverses the characters within a StringBuffer


object.

Output: olleH

137
StringBuffer Class:-
111 Karan 222 Aryan

 replace(): method replaces the string from specified start index to


the end index.

Output: Hello Java

138
StringBuffer Class:-
111 Karan 222 Aryan

 capacity():- method returns the current capacity of StringBuffer


object.

Output: 16

139
String v/s StringBuffer Class:-
111 Karan 222 Aryan

String StringBuffer
It is immutable means you cannot It is mutable means you can
modify. modify.
String class is slower than the StringBuffer class is faster than the
StringBuffer. String.
String is not safe for use by multiple String buffers are safe for use by
threads. multiple threads.

String Class not provides insert() StringBuffer Class provides insert()


Operation. Operation.
String Class not provides split() StringBuffer Class provides split()
Operation. Operation.
String class overrides the equals() StringBuffer class doesn't override
method of Object class. the equals() method of Object
class.

140
StringJoiner Class:-
111 Karan 222 Aryan

 Java StringJoiner class is included in the Java 8 version


that allows us to construct a sequence of characters
separated by a delimiter.
 It is located in java.util package and used to provide
utility to create a string by a user-defined delimiter.
 the delimiter can be anything like comma (,), colon(:)
etc. We can also pass suffix and prefix to the string
joiner object.
 Declaration:-
 public final class StringJoiner extends Object

141
StringJoiner Class:-
111 Karan 222 Aryan

Method Description

Public StringJoiner It adds a copy of the given CharSequence value as the


add(CharSequence next element of the StringJoiner value. If newElement is
newElement) null,"null" is added.

Public StringJoiner It adds the contents of the given StringJoiner without


merge(StringJoiner prefix and suffix as the next element if it is non-empty. If
other) the given StringJoiner is empty, the call has no effect.
It returns the length of the String representation of this
Public int length()
StringJoiner.

It sets the sequence of characters to be used when


Public StringJoiner
determining the string representation of this
setEmptyValue(CharSequ
StringJoiner and no elements have been added yet, that
ence emptyValue)
is, when it is empty.

It returns the current value, consisting of the prefix, and


public String toString()
the suffix or the empty value characters are returned.

142
StringJoiner Class:-
111 Karan 222 Aryan

143
StringJoiner Class:-
111 Karan 222 Aryan

144
Wrapper Class:-
111 Karan 222 Aryan

 Wrapper class wraps (encloses) around a data type and


gives it an object appearance.
 Wrapper classes are used to convert any data type into an
object.
 The primitive data types are not objects and they do not
belong to any class.
 So, sometimes it is required to convert data types into
objects in java.
 Wrapper classes include methods to unwrap the object and
give back the data type.
 The primary motivation for using wrapper classes is that
they allow us to treat primitive data types as objects, which
opens up opportunities for using them in various object-
oriented programming scenarios. 145
Wrapper Class:-
111 Karan 222 Aryan

 Eight wrapper classes exist in java.lang package that represent 8


data types:
Primitive Data Type Wrapper Class Unwrap Methods
byte Byte byteValue()
short Short shortValue()
int Integer intValue()
long Long longValue()
float Float floatValue()
double Double doubleValue()
char Character charValue()
boolean Boolean booleanValue()

146
Wrapper Class:-
111 Karan 222 Aryan

 Example:
 int k = 100;
 Integer it1 = new Integer(k);
 The int data type k is converted into an object, it1 using Integer
class.
 The it1 object can be used wherever k is required an object.
 To unwrap (getting back int from Integer object) the object it1.
Example:
 int m = it1.intValue();
 System.out.println(m*m); // prints 10000
 intValue() is a method of Integer class that returns an int data
type.

147
Wrapper Class:-
111 Karan 222 Aryan

 There are mainly two uses with wrapper classes.


 1) To convert simple data types into objects.
 2) To convert strings into data types (known as parsing
operations), here methods of type parseX() are used. (Ex.
parseInt())
 The wrapper classes also provide methods which can be used to
convert a String to any of the primitive data types, except
character.
 These methods have the format parse x() where x refers to any of
the primitive data types except char.
 To convert any of the primitive data type value to a String, we
use the valueOf() methods of the String class.

148
Wrapper Class:-
111 Karan 222 Aryan

149
Wrapper Class:-
111 Karan 222 Aryan

 Autoboxing and unboxing are convenient features introduced in


Java 5 that allow automatic conversion between primitive data
types and their corresponding wrapper classes.
 Wrapper classes also provide various utility methods for tasks
like parsing strings, converting between different bases, and
more. These classes are part of the java.lang package and are
automatically imported in Java programs.
 int x = Integer.parseInt("34"); // x=34
 double y = Double.parseDouble("34.7"); // y =34.7
 String s1= String.valueOf('a'); // s1="a"
 String s2=String.valueOf(true); // s2="true"

150

You might also like