0% found this document useful (0 votes)
10 views126 pages

chavan CH-2

The document provides an overview of classes and objects in Java, emphasizing the significance of encapsulation, inheritance, and polymorphism in object-oriented programming. It explains class structure, object creation, constructors, and methods, along with concepts like garbage collection and access modifiers. Additionally, it touches on Java's String, StringBuffer, and StringBuilder classes, as well as the Vector class and its functionalities.
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)
10 views126 pages

chavan CH-2

The document provides an overview of classes and objects in Java, emphasizing the significance of encapsulation, inheritance, and polymorphism in object-oriented programming. It explains class structure, object creation, constructors, and methods, along with concepts like garbage collection and access modifiers. Additionally, it touches on Java's String, StringBuffer, and StringBuilder classes, as well as the Vector class and its functionalities.
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/ 126

Classes and Objects in Java

Basics of Classes in Java

1
Contents

 Introduce to classes and objects in Java.

 Understand how some of the OO concepts


learnt so far are supported in Java.

 Understand important features in Java classes.

2
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.
3
Classes

 A class is a collection of fields (data) and


methods (procedure or function) that
operate on that data.

Circle

centre
radius

circumference()
area()

4
Classes

 A class is a collection of fields (data) and methods


(procedure or function) that operate on that data.
 The basic syntax for a class definition:
class ClassName [extends
SuperClassName]
{
[fields declaration]
[methods declaration]
}
 Bare bone class – no fields, no methods

public class Circle {


// my circle class
}
5
Adding Fields: Class Circle with fields

 Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle

 The fields (data) are also called the


instance varaibles.

6
Adding Methods
 A class with only data fields has no life. Objects
created by such a class cannot respond to any
messages.
 Methods are declared inside the body of the
class but immediately after the declaration of
data fields.
 The general form of a method declaration is:

type MethodName (parameter-list)


{
Method-body;
}

7
Adding Methods to Class Circle
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;
}
public double area() {
return 3.14 * r * r; Method Body

}
}
8
Class of Circle cont.

 aCircle, bCircle simply refers to a Circle


object, not an object itself.

aCircle bCircle

null null

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


9
Creating objects of a class

 Objects are created dynamically using the


new keyword.
 aCircle and bCircle refer to Circle objects
aCircle = new Circle() ; bCircle = new Circle() ;

10
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;

Before Assignment After Assignment


aCircle bCircle aCircle bCircle

P Q P Q

11
Automatic garbage collection

 The object Q
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.
12
The General Form of a Class
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}

13
Declaring Objects
Box mybox = new Box();

OR

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object

14
Assigning Object Reference Variables
 Box b1 = new Box();
 Box b2 = b1;

15
Constructors
 A constructor initializes an object immediately upon creation.
 It has the same name as the class in which it resides and is
syntactically similar to a method.
 Once defined, the constructor is automatically called
immediately after the object is created, before the new
operator completes.
 Constructors look a little strange because they have no return
type, not even void.
 It is the constructor’s job to initialize the internal state of an
object so that the code creating an instance will have a fully
initialized, usable object immediately.

16
Rules for creating Java constructor

1.There are two rules defined for the


constructor.
2.Constructor name must be the same as its
class name
3.A Constructor must have no explicit return
type.
4.A Java constructor cannot be abstract, static,
final, and synchronized

17
18
19
20
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.

21
Example of Parameterized constructor

22
Java Copy Constructor
 There is no copy constructor in Java. However, we can
copy the values from one object to another like copy
constructor in C++.
 There are many ways to copy the values of one object
into another in Java.
 They are:
 By constructor
 By assigning the values of one object into another
 By clone() method of Object class

23
Constructor Overloading in Java
 In Java, a constructor is just like a method but
without 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.

25
Example of Constructor Overloading
Call by Value
 There is only call by value in java, not call by reference.
 If we call a method passing a value, it is known as call
by value.
 The changes being done in the called method, is not
affected in the calling method.

28
call by reference
 In case of call by reference original value is changed if we made
changes in the called method.
 If we pass object in place of any primitive value, original value will
be changed. In this example we are passing object as a value.
The 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.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance
from the method.

30
31
32
33
The finalize( ) Method
 Sometimes an object will need to perform some
action when it is destroyed.
 For example, if an object is holding some non-Java
resource such as a file handle or window character
font, then you might want to make sure these
resources are freed before an object is destroyed.
 To handle such situations, Java provides a
mechanism
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
34
Java Object finalize() Method

• Finalize() is the method of Object class.


• This method is called just before an object is garbage
collected.
• finalize() method overrides to dispose system
resources, perform clean-up activities and minimize
memory leaks.

35
36
Garbage Collection
 objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation.

 In some languages, such as C++, dynamically allocated objects must be manually released
by use of a delete operator.

 It handles deallocation for you automatically. The technique that accomplishes this is
called garbage collection.

 It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed. There is no
explicit need to destroy objects as in C++.
 Garbage collection only occurs during the execution of your program. It will not occur
simply because one or more objects exist that are no longer used.

 Furthermore, different Java run-time implementations will take varying approaches to


garbage collection, but for the most part, you should not have to think about it while
writing
your program. 37
String
 String is immutable ( once created can not be changed )object .
 The object created as a String is stored in the Constant String Pool .
 Every immutable object in Java is thread safe ,that implies String is also thread
safe .
 String can not be used by two threads simultaneously
 String once assigned can not be changed.

String demo = " hello " ;


// The above object is stored in constant string pool and its value can not be
modified.
String indexOf
 The java string indexOf() method returns index of given character value
or substring.
 If it is not found, it returns -1. The index counter starts from zero.

66
StringBuffer
 StringBuffer is mutable means one can change the value of the
object .
 The object created through StringBuffer is stored in the heap .
 StringBuffer has the same methods as the StringBuilder , but each
method in StringBuffer is synchronized that is StringBuffer is
thread safe .

 StringBuffer demo1 = new StringBuffer("Hello") ;


// The above object stored in heap and its value can be changed .
 demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is
allowed in the StringBuffer

67
Constructors of StringBuffer class

 StringBuffer(): creates an empty string buffer with


the initial capacity of 16.
 StringBuffer(String str): creates a string buffer
with the specified string.
 StringBuffer(int capacity): creates an empty string
buffer with the specified capacity as length.

68
69
StringBuffer append() method

Hello Java
HJavaello
HJavalo

olleH
74
StringBuilder
 StringBuilder is same as the StringBuffer , that is it stores the
object in heap and it can also be modified .
 The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread safe.
 StringBuilder is fast as it is not thread safe

 StringBuilder demo2= new StringBuilder("Hello");


// The above object too is stored in the heap and its value can be modified

 demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the
StringBuilder

75
StringBuilder append() method

Hello Java

HJavaello
HJavalo

Hlo
olleH
80
Access Modifiers in Java

 There are two types of modifiers in


Java: access modifiers and non-
access modifiers.

81
 The access modifiers in Java specifies the accessibility or scope of
a field, method, constructor, or class.
 We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
 There are four types of Java access modifiers:
 Private: The access level of a private modifier is only within

the class. It cannot be accessed from outside the class.


 Default: The access level of a default modifier is only within

the package. It cannot be accessed from outside the package.


If you do not specify any access level, it will be the default.
 Protected: The access level of a protected modifier is within

the package and outside the package through child class. If


you do not make the child class, it cannot be accessed from
outside the package.
 Public: The access level of a public modifier is everywhere. It

can be accessed from within the class, outside the class, within
the package and outside the package.

82
83
Non-access modifiers

 There are many non-access modifiers,


such as static, abstract, synchronized,
native, volatile, transient, etc.

84
Vector
 Java Vector class comes under the java.util package.
 The vector class implements a growable array of
objects. Like an array, it contains the component that
can be accessed using an integer index.
 Vector is very useful if we don't know the size of an
array in advance or we need one that can change the
size over the lifetime of a program.
 Vector implements a dynamic array that means it can
grow or shrink as required. It is similar to the ArrayList,
but with two differences-
 Vector is synchronized.
 The vector contains many legacy methods that are not
the part of a collections framework
85
 The data structures provided by the Java utility
package are very powerful and perform a wide range of
functions.
 These data structures consist of the following interface
and classes −
 Enumeration
 BitSet
 Vector
 Stack
 Dictionary
 Hashtable
 Properties

86
The Enumeration
 The Enumeration interface isn't itself a data structure,
but it is very important within the context of other data
structures.
 The Enumeration interface defines a means to retrieve
successive elements from a data structure.
 For example, Enumeration defines a method called
nextElement that is used to get the next element in a
data structure that contains multiple elements.

87
The BitSet

 The BitSet class implements a group of


bits or flags that can be set and cleared
individually.
 This class is very useful in cases where
you need to keep up with a set of
Boolean values; you just assign a bit to
each value and set or clear it as
appropriate.

88
The Vector
 The Vector class is similar to a traditional Java
array, except that it can grow as necessary to
accommodate new elements.
 Like an array, elements of a Vector object can
be accessed via an index into the vector.
 The nice thing about using the Vector class is
that you don't have to worry about setting it to
a specific size upon creation; it shrinks and
grows automatically when necessary.

89
The Hashtable

 The Hashtable class provides a means of


organizing data based on some user-
defined key structure.
 For example, in an address list hash table
you could store and sort data based on a
key such as ZIP code rather than on a
person's name.

90
91
The Methods Defined by Vector

92
93
94
95
Vector Array
Vector is similar to array hold multiple Array is homogeneous collection of
objects and the objects can be data types.
retrieved using index value
Size of the vector can be changed Array is fixed size.
Vector automatically grows when they Array never grows when they run out
Run out of allocated space. of allocated space it attempt to do so,
result in overflow.
Vector provides extra method for No methods are provide for adding
adding removing and removing elements in case of
array
Vector is synchronized. Array is not synchronized

96
Wrappers:
Java’s Wrapper Classes for the
Primitives Types
Primitives & Wrappers
 Wrapper class in java provides the
mechanism to convert primitive into object
and object into primitive.
 autoboxing and unboxing feature
converts primitive into object and object
into primitive automatically.
 The automatic conversion of primitive into
object is known and autoboxing and vice-
versa unboxing.
 Change the value in Method: Java supports only call by
value. So, if we pass a primitive value, it will not change the
original value. But, if we convert the primitive value in an
object, it will change the original value.
 Serialization: We need to convert the objects into streams
to perform the serialization. If we have a primitive value, we
can convert it in objects through the wrapper classes.
 Synchronization: Java synchronization works with objects
in Multithreading.
 java.util package: The java.util package provides the
utility classes to deal with objects.
 Collection Framework: Java collection framework works
with objects only. All classes of the collection framework
(ArrayList, LinkedList, Vector, HashSet, LinkedHashSet,
TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects
only. 99
 Java has a wrapper class for each of the
eight primitive data types:
Primitive Wrapper Primitive Wrapper
Type Class Type Class
boolean Boolean float Float
byte Byte int Integer
char Character long Long
double Double short Short

100
101
102
103
104
105
106
Java Enums
 The Enum in Java is a data type which contains a fixed set
of constants.
 It can be used for days of the week (SUNDAY, MONDAY,
TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and
SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST), season (SPRING, SUMMER, WINTER, and
AUTUMN or FALL), colors (RED, YELLOW, BLUE,
GREEN, WHITE, and BLACK) etc. According to the Java
naming conventions, we should have all constants in capital
letters. So, we have enum constants in capital letters.
 Java Enums can be thought of as classes which have a fixed
set of constants (a variable that does not change).
 The Java enum constants are static and final implicitly. It is
available since JDK 1.5.
107
 Enums are used to create our own data type like classes. The
enum data type (also known as Enumerated Data Type) is
used to define an enum in Java. Unlike C/C++, enum in Java
is more powerful. Here, we can define an enum either inside
the class or outside the class.
 Java Enum internally inherits the Enum class, so it cannot
inherit any other class, but it can implement many interfaces.
We can have fields, constructors, methods, and main
methods in Java enum.

108
109
110
111
112
113
114
115
116
HashMap
 Java HashMap class implements the Map interface which allows us to
store key and value pair, where keys should be unique.
 If you try to insert the duplicate key, it will replace the element of the
corresponding key.
 It is easy to perform operations using the key index like updation,
deletion, etc. HashMap class is found in the java.util package.
 HashMap in Java is like the legacy Hashtable class, but it is not
synchronized.
 It allows us to store the null elements as well, but there should be only
one null key.
 Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and
V for value.
 It inherits the AbstractMap class and implements the Map interface.

118
 Java HashMap contains values based on
the key.
 Java HashMap contains only unique keys.
 Java HashMap may have one null key and
multiple null values.
 Java HashMap is non synchronized.
 Java HashMap maintains no order.
120
121
122
124
Java Annotation
 Java Annotation is a tag that represents the metadata
i.e. attached with class, interface, methods or fields to
indicate some additional information which can be used
by java compiler and JVM.
 Annotations in Java are used to provide additional
information, so it is an alternative option for XML and
Java marker interfaces.

125
 Built-In Java Annotations
 There are several built-in annotations in Java. Some
annotations are applied to Java code and some to other
annotations.
 Built-In Java Annotations used in Java code
@Override
@SuppressWarnings
@Deprecated
 Built-In Java Annotations used in other
annotations
@Target
@Retention
@Inherited
@Documented

126

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