Class

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 113

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() {
Method Body
return 3.14 * r * r;
}
}
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
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

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

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

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

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.

 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. 34
Overloading Methods
 In Java it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different.
 When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading.
 Method overloading is one of the ways that Java implements polymorphism.
 If you have never used a language that allows the overloading of methods, then the
concept may seem strange at first. But as you will see, method overloading is one of
Java’s most exciting and useful features.
 When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
 Thus, overloaded methods must differ in the type and/or number of
their parameters. While overloaded methods may have different return types, the
return type alone is insufficient to distinguish two versions of a method.
 When Java encounters a call to an overloaded method, it simply executes the
version of the method whose parameters match the arguments used in the call.

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.

 Terms used in Inheritance


 Class: A class is a group of objects which have common
properties. It is a template or blueprint from which objects are
created.
 Sub Class/Child Class: Subclass s is a class which inherits the other
class. It is also called a derived class, extended class, or child
class.
 Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a
parent class.
 Reusability: As the name specifies, reusability is a mechanism
which facilitates you to reuse the fields and methods of the
existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.
37
 The syntax of Java Inheritance
class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}  

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

 Method overriding is used to provide the


specific implementation of a method
which is already provided by its
superclass.
 Method overriding is used for runtime
polymorphism

51
Rules for Java Method Overriding

 The method must have the same name


as in the parent class
 The method must have the same
parameter as in the parent class.
 There must be an IS-A relationship
(inheritance).

52
53
54
55
56
57
58
Final Keyword In Java

 The final keyword in java is used to restrict


the user. The java final keyword can be used in
many context. Final can be:
 variable
 method
 class

59
1) Java final variable
If you make any variable as final, you cannot change

the value of final variable(It will be constant).


2) Java final method
If you make any method as final, you cannot override

it.

3) Java final class


If you make any class as final, you cannot extend 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  

Output:Compile Time Error

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();  
  }  
}

Output:Compile Time Error

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?

Yes, but only in constructor. For example:

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

 There are two types of modifiers in


Java: access modifiers and non-
access modifiers.

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

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.

76
77
Non-access modifiers

 There are many non-access modifiers,


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

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

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

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

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

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

You might also like