2. 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 “behavior” 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. 3
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]
}
Data Name
Data fields
Methods
4. 4
Bare bone class – no fields, no methods
Adding fields
The fields (data) are also called the instance variables.
public class Circle {
// my circle class
}
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
5. 5
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;
}
6. 6
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
7. 7
Declaring Objects
Objects are instances of class. Blocks of memory gets allocated for
these instance variables.
Object is the physical as well as logical entity whereas class is the
logical entity only.
For creating objects in Java the operator new is used
For example
test obj;
obj=new test();
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object
such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID.
The value of ID is not visible to the external user. But, it is used
internally by the JVM to identify each object uniquely
8. 8
Instance variable in Java
A variable which is created inside the class but outside the
method, is known as instance variable. Instance variable doesn't
get memory at compile time. It gets memory at run time when
object(instance) is created. That is why, it is known as instance
variable.
new keyword in Java
The new keyword is used to allocate memory at run time. All
objects get memory in Heap memory area.
9. Assigning object reference
variables
We can assign value of reference variable to another reference
variable.
Reference Variable is used to store the address of the variable.
Assigning Reference will not create distinct copies of Objects.
All reference variables are referring to same Object.
9
10. Adding methods to class
In java, a method is like function i.e. used to expose behavior of
an object.
Advantage of Method
1. Code Reusability
2. Code Optimization
Syntax
class class_name
{
declaration of member variables;
definition of methods
{……..}
}
10
11. 11
Object and Class Example: main within class
In this example, we have created a Student class that have two
data members id and name. We are creating the object of the
Student class by new keyword and printing the objects value.
Here, we are creating main() method inside the class.
Example
class Student{
int id;//field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference v
ariable
System.out.println(s1.name);
12. 12
}
}
Output
0
null
Object and Class Example: main outside class
We can have multiple classes in different java files or single
java file. If you define multiple classes in a single java source
file, it is a good idea to save the file name with the class name
which has main() method.
13. 13
class Student{
int id;
String name;
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
14. 14
Ways to initialize object
There are 3 ways to initialize object in java.
1. By reference variable
2. By method
3. By constructor
1. Object and Class Example: Initialization through reference
Initializing object simply means storing data into object.
class Student{
int id;
String name;
}
class TestStudent2{
15. 15
public static void main(String args[]){
Student s1=new Student();
s1.id=101; //initializing objects
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
//printing members with a white space
} }
Output
101 Sonoo
We can also create multiple objects and store information in
it through reference variable.
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
16. 16
Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class
and initializing the value to these objects by invoking the
insertRecord method. Here, we are displaying the state (data) of
the objects by invoking the displayInformation() method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
18. 18
Object and Class Example: Initialization through constructor
class Student4{
int id;
String name;
Student4(int i,String n){ // Constructor
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
} }
19. 19
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:
1. By new keyword
2. By newInstance() method
3. By clone() method
4. By deserialization
5. By factory method etc.
20. 20
returning a value
Method can return a value by using “return” keyword.
Return Type can be “Void” means it does not return any value.
There are some important things to understand about returning
values
1. The type of data returned by a method must be compatible
with the return type specified by the method.
2. The variable receiving the value returned by a method must
also be compatible with the return type specified for the
method.
3. Parameters should be passed in sequence and they must be
accepted by method in the same sequence
21. 21
constructors
Constructor in java is a special type of method that is used to
initialize the object.
Java constructor is invoked at the time of object creation. It
constructs the values i.e. provides data for the object that is why
it is known as constructor.
Rules for creating java constructor
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
1. Default constructor (no-argument constructor)
2. Parameterized constructor
3. Copy constructor
22. 22
this keyword
In java, this is a reference variable that refers to the current
object.
Usage of java this keyword
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the
method.
23. 23
Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.
To do so, we were using free() function in C language and delete() in
C++. But, in java it is performed automatically. So, java provides
better memory management.
Advantage of Garbage Collection
a. It makes java memory efficient because garbage collector removes
the unreferenced objects from heap memory.
b. It is automatically done by the garbage collector(a part of JVM) so
we don't need to make extra efforts.
How can an object be unreferenced?
1. By nulling the reference
2. By assigning a reference to another
3. By anonymous object etc.
24. 24
Finalize() method
The finalize() method is invoked each time before the object is
garbage collected. This method can be used to perform cleanup
processing. This method is defined in Object class as:
protected void finalize(){}
The Garbage collector of JVM collects only those objects that
are created by new keyword. So if you have created any object
without new, you can use finalize method to perform cleanup
processing .
25. 25
Overloading methods
a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of
the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but
there can be any number of arguments, if you write the method
such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you. So, we perform
method overloading to figure out the program quickly. Method
overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
26. 26
Argument Passing
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.
Note: When a simple type is passed to a method, it is done by
call-by-value. Objects are passed by call-by-reference
27. 27
Object as parameter
We can pass Object of any class as parameter to a method in
java.
We can access the instance variables of the object passed
inside the called method.
Different Ways of Passing Object as Parameter :
Way 1 : By directly passing Object Name
Way 2 : By passing Instance Variables one by one
Way 3 : We can pass only public data of object to the
Method
28. 28
Returning objects
Passing objects to a method indirectly makes call by
reference mechanism. Even though java is having only "call
by value" mechanism, we can achieve "call reference" by
passing objects.
A method can return any type of data, including class types
that you create.
If you have to reuse the object, you can pass it through
method or constructor call. In such case, object can be used
in multiple methods or classes.
29. 29
Access Control
Access control specifies the accessibility of code. By using these
you can specify the scope of data, method, class etc.
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract,
synchronized, native, volatile, transient etc. Here, we will learn
access modifiers.
30. 30
Static
The static keyword in java is used for memory management
mainly. We can apply java static keyword with variables,
methods, blocks and nested class. The static keyword belongs
to the class than instance of the class.
The static can be:
a. variable (also known as class variable)
b. method (also known as class method)
c. block
d. nested class
31. 31
Final
The final keyword in java is used to restrict the user. The
java final keyword can be used in many context. Final can
be:
a. variable
b. method
c. class
The final keyword can be applied with the variables, a final
variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also
which will be initialized in the static block only. We will
have detailed learning of these. Let's first learn the basics of
final keyword.
32. 32
Nested and Inner classes
In Java, just like methods, variables of a class too can have another class
as its member. Writing a class within another is allowed in Java. The
class written within is called the nested class, and the class that holds
the inner class is called the outer class.
Java inner class or nested class is a class i.e. declared inside the class or
interface.
We use inner classes to logically group classes and interfaces in one
place so that it can be more readable and maintainable.
Advantage of java inner classes
1) Nested classes represent a special type of relationship that is it can
access all the members (data members and methods) of outer
class including private.
2) Nested classes are used to develop more readable and
maintainable code because it logically group classes and interfaces in
one place only.
3) Code Optimization: It requires less code to write.
33. 33
Command line arguments
The java command-line argument is an argument i.e. passed at
the time of running the java program.
The arguments passed from the console can be received in the
java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the
program for the different values. You can pass N (1,2,3 and so
on) numbers of arguments from the command prompt.
34. 34
Variable-length arguments
The varrags allows the method to accept zero or muliple
arguments. Before varargs either we use overloaded method or
take an array as the method parameter but it was not considered
good because it leads to the maintenance problem. If we don't
know how many argument we will have to pass in the method,
varargs is the better approach.
Advantage of Varargs:
We don't have to provide overloaded methods so less code.
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax
is as follows:
return_type method_name(data_type... variableName){}
35. 35
Inheritance
Inheritance in java is a mechanism in which one object acquires
all the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new
classes that are built upon existing classes. When you inherit from
an existing class, you can reuse methods and fields of parent class,
and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known
as parent-child relationship.
Why use inheritance in java?
1. For Method Overriding (so runtime polymorphism can be
achieved).
2. For Code Reusability.
36. 36
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new
class that derives from an existing class. The meaning of
"extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called
parent or super class and the new class is called child or
subclass.
Note: Multiple inheritance is not supported in java
through class.
38. 38
Using Super
The super keyword in java is a reference variable which is used to
refer immediate parent class object.
Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super
reference variable.
Usage of java super Keyword
1. super can be used to refer immediate parent class instance
variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class
constructor.
40. 40
Constructor Call Sequence
public class SequenceInputStream extends InputStream
Constructors of SequenceInputStream class
Constructor Description
SequenceInputStream
(InputStream s1,
InputStream s2)
creates a new input
stream by reading the
data of two input stream
in order, first s1 and then
s2.
SequenceInputStream
(Enumeration e)
creates a new input
stream by reading the
data of an enumeration
whose type is
InputStream.
41. 41
Dynamic method dispatch
Runtime polymorphism or Dynamic Method Dispatch is a
process in which a call to an overridden method is resolved at
runtime rather than compile-time.
In this process, an overridden method is called through the
reference variable of a superclass. The determination of the
method to be called is based on the object being referred to by the
reference variable.
43. 43
Abstract Classes
Abstraction is a process of hiding the implementation details and
showing only functionality to the user. Another way, it shows
only important things to the user and hides the internal details for
example sending sms, you just 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.
A class that is declared as abstract is known as abstract class. It
needs to be extended and its method implemented. It cannot be
instantiated.
Syntax
abstract class class_name{}
Abstract method is declared as abstract and does not have
implementation is known as abstract method.
Example: abstract void printStatus();//no body and abstract
44. 44
Object Class
The Object class is the parent class of all the classes in java by
default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose
type you don't know. Notice that parent class reference variable can
refer the child class object, know as upcasting.
Methods of object class
Method Description
public final Class getClass() returns the Class class object of this
object. The Class class can further be
used to get the metadata of this class.
public int hashCode() returns the hashcode number for this
object.
public boolean equals(Object
obj)
compares the given object to this
object.
45. 45
Method Description
protected Object clone() throws
CloneNotSupportedException
creates and returns the exact copy (clone)
of this object.
public String toString() returns the string representation of this
object.
public final void notify() wakes up single thread, waiting on this
object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this
object's monitor.
public final void wait(long
timeout)throws
InterruptedException
causes the current thread to wait for the
specified milliseconds, until another
thread notifies (invokes notify() or
notifyAll() method).
public final void wait(long
timeout,int nanos)throws
InterruptedException
causes the current thread to wait for the
specified milliseconds and nanoseconds,
until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait()throws
InterruptedException
causes the current thread to wait, until
another thread notifies (invokes notify() or
notifyAll() method).
protected void finalize()throws
Throwable
is invoked by the garbage collector before
object is being garbage collected.
47. A java package is a group of similar types of classes, interfaces
and sub-packages.
Package in java can be categorized in two form, built-in package
and user-defined package.
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-
defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so
that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
47
49. 49
Defining a package
The package keyword is used to create a package in java.
For example
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given
below:
javac -d directory javafilename
For example
javac -d . Simple.java
50. The -d switch specifies the destination where to put the generated
class file. You can use any directory name like /home (in case of
Linux), d:/abc (in case of windows) etc. If you want to keep the
package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run
the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file
i.e. it represents destination. The . represents the current folder.
50
51. 51
Finding Package and
CLASSPATH
In Java, Packages are mirrored directories i.e. the source program
and the generated .class file are saved in the folders which have
the same name similar to the package name.
There are three ways how java run-time system find a package in
Java program.
First: By default the java run-time system considers the current
directory which you are working as starting directory and checks
for the package defined and finds it if it is present that directory.
Second: To specify the directory path by setting
the CLASSPATH environment variable.
Third: Using -classpath option while compiling and running the
java program to specify the path to your classes.
The following program shows the above three ways how a java
run-time system finds the package.
52. To display the current CLASSPATH variable, use the following
commands in Windows and UNIX (Bourne shell) −
In Windows → C:> set CLASSPATH
In UNIX → % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use
−
In Windows → C:> set CLASSPATH =
In UNIX → % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable −
In Windows → set CLASSPATH =
C:usersjackjavaclasses
In UNIX → % CLASSPATH = /home/jack/java/classes;
export CLASSPATH
52
53. 53
Access Protection
Access modifiers define the scope of the class and its members
(data and methods). For example, private members are accessible
within the same class members (methods). Java provides many
levels of security that provides the visibility of members (variables
and methods) within the classes, subclasses, and packages.
Packages are meant for encapsulating, it works as containers for
classes and other sub-packages. Class acts as containers for data
and methods. There are four categories, provided by Java
regarding the visibility of the class members between classes and
packages:
1. Subclasses in the same package
2. Non-subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor subclasses
54. The three main access modifiers private,
public and protected provides a range of ways to access required
by these categories.
54
55. 55
Importing packages
import keyword is used to import built-in and user-defined
packages into your java source file. So that your class can refer to
a class that is in another package by directly using its name.
There are 3 different ways to refer to class that is present in
different package
1. Using fully qualified name (But this is not a good practice.)
Example :class MyDate extends java.util.Date { //statement; }
2. import the only class you want to use
Example : import java.util.Date; class MyDate extends Date {
//statement. }
3. import all the classes from the particular package
Example : import java.util.*; class MyDate extends Date {
//statement; }
56. 56
Static import
static import is a feature that expands the capabilities
of import keyword. It is used to import static member of a class.
Using static import, it is possible to refer to the static member
directly without its class name. There are two general form of
static import statement.
1. The first form of static import statement, import only a single
static member of a class
Syntax: import static package.class-name.static-member-name;
Example: import static java.lang.Math.sqrt; //importing static
method sqrt of Math class
2. The second form of static import statement, imports all the
static member of a class
Syntax: import static package.class-type-name.*;
Example: import static java.lang.Math.*; //importing all static
member of Math class
57. 57
Interfaces
Interface is a pure abstract class. They are syntactically similar to
classes, but you cannot create instance of an Interface and their
methods are declared without any body. Interface is used to achieve
complete abstraction in Java. When you create an interface it
defines what a class can do without saying anything about how the
class will do it.
Syntax :
interface interface_name { }
Example of Interface
interface Moveable
{ int AVERAGE-SPEED=40; void move(); }
58. Why use Java interface?
1. There are mainly three reasons to use interface. They are given
below.
2. It is used to achieve abstraction.
3. By interface, we can support the functionality of multiple
inheritance.
4. It can be used to achieve loose coupling.
Interface fields are public, static and final by default, and methods
are public and abstract.
58
59. Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class,
an interface extends another interface but a class implements an
interface.
59
60. Java Interface Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
60
61. Rules for using Interface
o Methods inside Interface must not be static, final, native or
strictfp.
o All variables declared inside interface are implicitly public static
final variables(constants).
o All methods declared inside Java Interfaces are implicitly public
and abstract, even if you don't use public or abstract keyword.
o Interface can extend one or more other interface.
o Interface cannot implement a class.
o Interface can be nested inside another interface.
61
62. Abstract class Interface
Abstract class is a class which contain
one or more abstract methods, which has
to be implemented by its sub classes.
Interface is a Java Object containing
method declaration but no
implementation. The classes which
implement the Interfaces must provide
the method definition for all the
methods.
Abstract class is a Class prefix with an
abstract keyword followed by Class
definition.
Interface is a pure abstract class which
starts with interface keyword.
Abstract class can also contain concrete
methods.
Whereas, Interface contains all abstract
methods and final variable declarations.
Abstract classes are useful in a situation
that Some general methods should be
implemented and specialization behavior
should be implemented by child classes.
Interfaces are useful in a situation that all
properties should be implemented.
62
Difference between an interface and an abstract class?
63. 63
Variables in Interfaces
Same as access protection point of packages
Access modifiers (public, private, protected)
64. 64
Extending Interfaces
An interface can extend another interface in the same way that a
class can extend another class. The extends keyword is used to
extend an interface, and the child interface inherits the methods of
the parent interface.
Extending Multiple Interfaces
A Java class can only extend one parent class. Multiple inheritance
is not allowed. Interfaces are not classes, however, and an
interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are
declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and
Event, it would be declared as −
Example
public interface Hockey extends Sports, Event
65. 65
Instance of operator
The java instanceof operator is used to test whether the object is
an instance of the specified type (class or subclass or interface).
The instanceof in java is also known as type comparison
operator because it compares the instance with type. It returns
either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Simple example of java instanceof
class Simple1{
public static void main(String args[])
{ Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true }
}
Output:true