Class
Class
Class
1
Contents
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
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
Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
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:
7
Adding Methods to Class Circle
public class Circle {
aCircle bCircle
null null
10
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P Q P Q
11
Automatic garbage collection
The object Q
does not have a
reference and cannot be used in future.
13
Declaring Objects
Box mybox = new Box();
OR
14
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
15
Introducing Methods
type name(parameter-list)
{
// body of method
}
16
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.
17
Rules for creating Java constructor
18
19
20
21
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.
22
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.
23
24
25
26
27
28
29
30
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
}
31
Java Object finalize() Method
32
33
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.
35
Inheritance
Inheritance is one of the feature of object-oriented programming because
it allows the creation of hierarchical classifications.
Using inheritance, you can create a general class that defines traits
common to a set of related items.
This class can then be inherited by other, more specific classes, each
adding those things that are unique to it. In the terminology of Java, a
class that is inherited is called a superclass.
The class that does the inheriting is called a subclass. Therefore, a
subclass is a specialized version of a superclass. It inherits all of the
instance variables and methods defined by the superclass and adds its
own, unique elements.
36
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
38
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary
is:"+p.salary);
System.out.println("Bonus of Programmer
is:"+p.bonus);
}
}
Output :-Programmer salary
is:40000.0
Bonus of programmer 39
40
41
42
43
44
45
Using super
The super keyword in java is a reference variable that is used
to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of
parent class is created implicitly i.e. referred by super
reference variable.
Usage of java super Keyword
super is used to refer immediate parent class instance variable.
super() is used to invoke immediate parent class constructor.
super is used to invoke immediate parent class method implicitly i.e. referred
by super reference variable.
46
47
48
49
Method Overriding
In a class hierarchy, when a method in a subclass has the
same name and type signature as a method in its superclass,
then the method in the subclass is said to override the method
in the superclass.
When an overridden method is called from within a
subclass, it will always refer to the version of that method
defined by the subclass.
The version of the method defined by the superclass will be
hidden.
50
Usage of Java Method Overriding
51
Rules for Java Method Overriding
52
53
54
55
56
57
58
Final Keyword In Java
59
1) Java final variable
If you make any variable as final, you cannot change
it.
60
Example of final variable
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
61
Example of final method
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
62
Example of final class
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
63
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it.
For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Test it NowOutput:running...
64
Que) Can we initialize blank final variable?
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}
Test it NowOutput:70
65
66
67
Abstraction in Java
Abstraction is a process of hiding the implementation details
and showing only functionality to the user.
Another way, it shows only essential things to the user and
hides the internal details, for example, sending SMS where
you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of
how it does it.
68
Abstraction in Java
A class which is declared as abstract is known as an
abstract class.
It can have abstract and non-abstract methods.
It needs to be extended and its method
implemented.
It cannot be instantiated.
69
70
71
72
73
74
Access Modifiers in Java
75
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
can be accessed from within the class, outside the class, within
the package and outside the package.
76
77
Non-access modifiers
78
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
79
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
80
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.
81
The BitSet
82
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.
83
The Hashtable
84
85
The Methods Defined by Vector
86
87
88
89
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
90
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.
93
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
94
95
96
97
98
99
100
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.
101
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.
102
103
104
105
106
107
108
109
110
111
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.
112
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
113