core-java
core-java
By : Ghanshyam Dhomse
Agenda
1. What is JAVA?
2. Features of Java
3. Hello World Program
4. Brief Concept JDK , JRE and JVM
5. Java OOP Concepts
2
Project Execution Traditional Approach
&
History
ge
O f Java?
a
rm u Jav
fo n g
aV
at L a
er
si on
a ing
u s ed? ?
i s
re it
m
Pl
h e
am
W Features of java??
gr
o
Pr
s
re
viro
Java O
tu
n men O
fea
Ja t P Con
va cepts?
ew
Vi
aN
rtu
al t Kit
Jav
M me n
ac ve l op
h De
in
e Java
3 3
What is Java?
4
What it is Used?
5
Types of Java Application?
There are mainly 4 type of applications that can be created using java:
1) Standalone Application
An application that runs on the server side and creates dynamic page, is
called web application. Currently, servlet, jsp, struts, jsf etc. technologies
are used for creating web applications in java.
6
Types of Java Application
3) Enterprise Application
4) Mobile Application
7
Brief History of JAVA
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991.
originally designed for small, embedded systems in electronic appliances
like set-top boxes.
initially called Oak and was developed as a part of the Green project
In 1995, Oak was renamed as "Java". Java is just a name not an acronym.
originally developed by James Gosling at Sun Microsystems(which is now
a subsidiary of Oracle Corporation) and released in 1995.
JDK 1.0 released in(January 23, 1996).
8
Features of Java
Simple
Object-Oriented
Platform Independent
Secured
Robust
Architecture Neutral
Portable
High Performance
Distributed
Multi-threaded
9
Java is Simple??
10
Java is Object Oriented?
11
Java is Platform Independent?
13
Java is Secure
• No explicit pointer
• Programs run inside virtual machine sandbox.
• Class loader- adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
• Byte code Verifier- checks the code fragments for illegal code that can
violate accesss right to objects.
• Security Manager- determines what resources a class can access such as
reading and writing to the local disk.
Some sucurity can also be provided by through SSL, JAAS,cryptography
etc.
14
Java is Robust
15
C++ Program Execution
16
Java Program Execution
17
Portable High-Performance Distributed
Portable
We can create distributed applications in java. RMI and EJB are used for
creating distributed applications. We may access files by calling the
methods from any machine on the internet.
18
Multi-Threaded
Multi-threaded
19
Hello Word Java Program!!
20
Hello Word Java Program!!
21
Understanding First Java Program
22
Understanding First Java Program
To write the simple program, open notepad and write simple program as
displayed below:
23
Understanding First Java Program
24
Understanding First Java Program
javac Simple.java
To execute:
java Simple
Output: Hello Java
25
What happen at Compile Time?
At compile time, java file is compiled by Java Compiler (It does not interact
with OS) and converts the java code into bytecode.
26
Step follow at Compile Time..
27
How many ways, we can write a java program?
There are many ways to write a java program. The modifications that can be done
in a java program are given below:
1) By changing sequence of the modifiers, method prototype is not changed.
Let's see the simple code of main method.
static public void main(String args[])
2) subscript notation in java array can be used after type, before variable or after
variable.
Let's see the different codes to write the main method.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
28
How many ways, we can write a java program?
29
How to Set Permanent Path of JDK?
Class loader: is the subsystem of JVM that is used to load class files.
Bytecode Verifier: checks the code fragments for illegal code that can
violate accesss right to objects.
Interpreter: read bytecode stream then execute the instructions.
Setting Permanent Path of JDK in Windows:
For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer properties -> advanced tab -> environment variables -
> new tab of user variable -> write path in variable name -> write path of
bin folder in variable value -> ok -> ok -> ok
30
How to Set Permanent Path of JDK?
31
Difference between JDK,JRE and JVM
32
Difference between JDK,JRE and JVM
JRE
JRE is an acronym for Java Runtime Environment. It is used to provide
runtime environment. It is the implementation of JVM. It physically Exists.
It contains set of libraries + other files that JVM uses at runtime.
33
Difference between JDK,JRE and JVM
34
Difference between JDK,JRE and JVM
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains
JRE + development tools.
35
JVM (Java Virtual Machine)
36
JVM (Java Virtual Machine)
37
Internal Architecture of Java
38
Internal Architecture of Java
39
Internal Architecture of Java
41
Java OOPs Concepts
42
Advantage of OOPs over Procedure-oriented
programming language
43
What is difference between object-oriented programming
language and object-based programming language?
44
Naming convention
Naming convention
By using standard Java naming conventions they make their code easier to
read for themselves and for other programmers. Readability of Java code
is important because it means less time is spent trying to figure out what
the code does.
45
Naming Convention
Object
A runtime entity that has state and behaviour is known as an object. For
example: chair, table, pen etc. It can be tengible or intengible (physical or
logical).
An object has three characteristics:
state: represents the data of an object.
behavior: represents the behavior of an object.
identity: Object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user, but is used internally by
the JVM to identify each object uniquely.
48
Class
For Example: Pen is an object. Its name is Reynolds, color is white etc.
known as its state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from
which objects are created. So object is the instance(result) of a class.
Class - A class is a group of objects that have common property.
It is a template or blueprint from which objects are created.
A class in java can contain: Data member
Method
Constructor
Block
49
Syntax of Class declaration
50
Simple Example of Object and Class
class Student {
int id; //data member (also instance variable)
String name; //data member(also instance variable)
public static void main(String args[])
{
Student s1=new Student(); //creating an object of Student
System.out.println(s1.id+" "+s1.name);
}
} Output: 0 null
51
Simple Example of Object and Class
Instance variable
A variable that 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 runtime when object(instance) is
created.That is why, it is known as instance variable.
Method
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
Code Reusability & Code Optimization
new keyword - The new keyword is used to allocate memory at runtime.
52
Example of Object and class that maintains the
records of students
In this example, we are creating the two objects of Student class and
initializing the value to these objects by invoking the insertRecord method
on it. 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) { //method
rollno=r;
name=n;
}
53
Example of Object and class that
maintains the records of students
54
Diagram View
object gets the memory in Heap area and reference variable refers to the object
allocated in the Heap memory area. Here, s1 and s2 both are reference variables
that refer to the objects allocated in memory.
55
Another Example
class Rectangle {
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
public static void main(String args[]) {
56
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
57
Different ways to create an object in Java?
Annonymous object
Annonymous simply means nameless. An object that have no reference is
known as annonymous object.
58
Anonymous Object is Use only Once.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5); //calling method with annonymous object
} } Output: Factorial is 120
59
Method Overloading in Java
60
Method Overloading in Java
If we have to perform only one operation, having the same name of the
methods increases the readability of the program.
Advantage of method overloading?
61
Example of Method Overloading by
changing the no. of arguments
62
Why Method Overloading is not possible by
changing the return type of method?
In java, method overloading is not possible by changing the return type of the method
because there may occur ambiguity. Let's see how ambiguity may occur:
class Calculation { int sum(int a,int b) { System.out.println(a+b); }
double sum(int a,int b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
int result=obj.sum(20,20); //Compile Time Error } }
int result=obj.sum(20,20); //Here how can java determine which sum() method
should be called
63
Can we overload main() method?
64
Method Overloading and TypePromotion
65
Method Overloading and TypePromotion
1. Types of constructors
Default Constructor
Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value ?
4. Copying the values of one object into another?
5. Does constructor perform other task instead initialization?
67
Constructor
68
Types of constructors
Types of constructors
There are two types of constructors:
default constructor (no-arg constructor)
parameterized constructor
69
Default Constrcture
1) Default Constructor
A constructor that have no parameter is known as default constructor.
71
Parameterized Constructor
Parameterized constructor
A constructor that have parameter is known as parameterized
constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the
distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that
have two parameters. We can have any number of parameters in the
constructor.
72
Example
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display(); } } Output:111 Karan 222 Aryan
73
Constructor Overloading
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any
number of constructors that differ in parameter lists. The compiler
differentiates these constructors by taking into account the number of
parameters in the list and their type.
Example of Constructor Overloading
//Program of constructor overloading
class Student
{ int id; String name; int age;
74
Constructor Overloading Example
Student(int i,String n)
{ id = i; name = n; }
Student(int i,String n,int a)
{ id = i; name = n; age=a; }
void display()
{ System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25); s1.display();
s2.display(); }} Output:1 11 Karan 0 222 Aryan 25
75
What is the difference between constructor and
method ?
Constructor vs Method
Constructor is used to initialize the state of an object.
Method is used to expose behavior of an object.
Constructor must not have return type.
Method must have return type.
Constructor is invoked implicitly.
Method is invoked explicitly.
The java compiler provides a default constructor if you don't have any constructor.
Method is not provided by compiler in any case.
Constructor name must be same as the class name.
Method name may or may not be same as class name.
76
Copying the values of one object to another like copy
constructor in C++
There are many ways to copy the values of one object into another. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another
using constructor.
77
Example
79
Copying the values of one object to another
without constructor
80
Copying the values of one object to another
without constructor
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Output:111 Karan
111 Karan
Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling method etc. You can perform
any operation in the constructor as you perform in the method.
81
static keyword
1. Static variable
2. Program of counter without static variable
3. Program of counter with static variable
4. Static method
5. Restrictions for static method
6. Why main method is static ?
7. Static block
8. Can we execute a program without main method ?
82
Static variable
The static keyword is used in java mainly for memory management. We may apply
static keyword with variables, methods and blocks. The static keyword belongs to
the class than instance of the class.
The static can be:
variable (also known as class variable)
method (also known as class method)
block
1) static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees, college name of
students etc.
83
Advantages Of Static variable
The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
class Student { int rollno; String name; String college="ITS";}
Suppose there are 500 students in my college, now all instance data members will
get memory each time when object is created.
All student have its unique rollno and name so instance data member is good.
Here, college refers to the common property of all objects.
If we make it static, this field will get memory only once. Note:static field is shared
by all objects.
84
Example of static variable
85
Static Diagram
86
Program of counter without static variable
87
Program of counter by static variable
88
static method
2) 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 object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• static method can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects(static field).
class Student{
int rollno; String name; static String college = "ITS";
static void change(){ college = “SNJB"; }
89
Example of static method
90
Restrictions for static method
91
why main method is static?
92
Example of static block
class A
{ static{System.out.println("static block is invoked");}
public static void main(String args[])
{ System.out.println("Hello main"); }}
Output:static block is invoked Hello main
Can we execute a program without main() method?
Ans) Yes, one of the way is static block but in previous version of JDK not
in JDK 1.7.
93
this keyword
1. this keyword
2. Usage of this keyword
to refer the current class instance variable
to invoke the current class constructor
to invoke the current class method
to pass as an argument in the method call
to pass as an argument in the constructor call
to return the current class instance
94
Usage of this keyword
Suggestion:If you are beginner to java, lookup only two usage of this
keyword.
95
Usage of this keyword
96
this keyword usages
1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword
resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given
c lass student{
int id; String name; student(int id,String name){ id = id; name = name; }
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
student s1 = new student(111,"Karan"); student s2 = new student(321,"Aryan");
s1.display(); s2.display(); } } Output:0 null 0 null
97
Solution of the above problem by this keyword
In the above example, parameter (formal arguments) and instance variables are
same that is why we are using this keyword to distinguish between local variable
and instance variable.
Solution of the above problem by this keyword
class Student{ int id; String name;
student(int id,String name) { this.id = id; this.name = name; }
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan");
s1.display(); s2.display(); }} Output:111 Karan 222 Aryan
98
Program where this keyword is not required
99
this() invoke current class constructor
100
Example
101
Where to use this() constructor call?
102
Example
103
this keyword invoke the current class
method (implicitly)
3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while
invoking the method.
class S{ void m(){ System.out.println("method is invoked"); }
void n(){ this.m(); //no need because compiler does it for you. }
void p(){ n(); //complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S(); s1.p(); } } Output:method is invoked
104
Compiler add this keyword ( implicitly )
105
this keyword passed as an argument in
the method
4) The this keyword can be passed as an argument in the method.
The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling.
class S { void m(S obj){ System.out.println("method is invoked"); }
void p(){ m(this); }
public static void main(String args[]){
S s1 = new S();
s1.p();
} }
Output: method is invoked
Application of this that can be passed as an argument: In event handling (or) in a situation where we have
to provide reference of a class to another one.
106
this keyword can be passed as argument in the
constructor call
107
this keyword can be used to return current
class instance.
6) The this keyword can be used to return current class instance.
We can return the this keyword as an statement from the method. In such case,
return type of the method must be the class type (non-primitive). Let's see the
Syntax of this that can be returned as a statement
return_type method_name() { return this; }
Example of this keyword that you return as a statement from the method
class A{ A getA(){ return this; } void msg(){System.out.println("Hello java");} }
class Test{
public static void main(String args[]){
new A().getA().msg();
} } Output:Hello java
108
Inheritance (Object-Oriented Programming)
Syntax of Inheritance
class Subclass-name extends Superclass-name { //methods and fields}
The keyword extends indicates that you are making a new class that derives from
an existing class. In the terminology of Java, a class that is inherited is called a
super class.
The new class is called a subclass.
110
Example of inheritance
111
Types of Inheritance:
112
Multiple inheritance is not supported in java in
case of class.
113
Aggregation in Java
114
Simple Example of Aggregation
System.out.println(result); } } Output:78.5
115
When use Aggregation?
116
Example
Address.java
public class Address { String city, state, country;
public Address (String city, String state, String country)
{ super(); this.city = city; this.state = state; this.country = country;} }
Emp.java
public class Emp {int id; String name; Address address;
public Emp(int id, String name,Address address)
{ this.id = id; this.name = name; this.address=address; } void display()
{System.out.println(id+"+name);
System.out.println(address.city+" "+address.state+" "+address.country);}
117
Example
118
Method Overriding in Java
119
Rules for Method Overriding
121
Difference between method Overloading
and Method Overriding.
122
Difference between method Overloading
and Method Overriding.
Method Overloading vs Method Overriding
1) Method overloading is used to increase the readability of the program.
Method overriding is used to provide the specific implementation of the
method that is already provided by its super class.
2) method overlaoding is performed within a class.
Method overriding occurs in two classes that have IS-A relationship.
3) In case of method overloading parameter must be different.
In case of method overriding parameter must be same.
123
super keyword
super keyword:
super is a reference variable that is used to refer immediate parent class
object.
Uses of 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.
124
Problem without super keyword
125
Solution by super keyword
126
Example of super keyword
127
Super() provide the first statement by
compiler
128
super() is provided by the compiler(implicitely)
129
Program of super that can be used to invoke
method of parent class
130
Program in case super is not required
131
Instance initializer block:
132
Why use instance intializer block
What is the use of instance initializer block while we can directly assign
a value in instance data member? For example:
class Bike{ int speed=100;}
Why use instance initializer block?
Suppose I have to perform some operations while assigning value to
instance data member e.g. a for loop to fill a complex array or error
handling etc.
133
Example of Instance initializer block
134
What is invoked firstly instance initializer block or
constructor?
135
The java compiler copies the code of instance
initializer block in every constructor.
136
final keyword:
final keyword:
1. Final variable
2. Final method
3. Final class
4. Is final method inherited ?
5. Blank final variable
6. Static blank final variable
7. Final parameter
8. Can you declare a final constructor
137
final keyword
The final keyword in java is used to restrict the user. The final keyword
can be used in many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, that have no value it
is called blank 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.
138
final variable
1) final variable:
If you make any variable as final, you cannot change the value of final
variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of
this variable, but It can't be changed because final variable once assigned
a value can never be changed.
class Bike{ final int speedlimit=90;//final variable
void run(){ speedlimit=400; } public static void main(String args[]){ Bike
obj=new Bike(); obj.run(); }} Output:Compile Time Error
139
final method
2) final method
If you make any method as final, you cannot override it.
Example of final method
3) final class:
If you make any class as final, you cannot extend it.
Example of final class
class Bike
{
final void run(){System.out.println("running...");}}
class Honda extends Bike
{ public static void main(String args[])
{ new Honda().run(); }} Output:running...
142
What is blank final variable?
143
static blank final variable
144
What is final parameter?
class Bike {
int cube(final int n){ n=n+2; //can't be changed as n is final n*n*n;
}
public Static void main(String args[]){ Bike b=new Bike(); b.cube(5); }}
Output: Compile Time Error
Can we declare a constructor as final?
No, because constructor is never inherited.
145
Abstract class in Java
Abstraction
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.
Abstraction lets you focus on what the object does instead of how it does
it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
146
Abstract class
Abstract class
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 to declare the abstract class
abstract class <class_name>{} abstract method
A method that is declared as abstract and does not have implementation
is known as abstract method.
Syntax to define the abstract method
abstract return_type <method_name>();//no braces{}
147
Example of abstract class
148
Real scenario of abstract class
149
Real scenario of abstract class
150
Example of abstract class that have
method body
Abstract class having constructor, data member, methods etc.
Note: An abstract class can have data member,abstract method,method body,
constructor and even main() method.
//example of abstract class that have method body
abstract class Bike{
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{ void run(){System.out.println("running safely..");}
public static void main(String args[]){ Bike obj = new Honda(); obj.run();
obj.changeGear(); } } Output:running safely..
151
Example of abstract class having constructor,
field and method
abstract class Bike
{
int limit=30; Bike() {System.out.println("constructor is invoked");}
void getDetails(){System.out.println("it has two wheels");} abstract void run(); }
class Honda extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){ Bike obj = new Honda(); obj.run();
obj.getDetails(); System.out.println(obj.limit); } }
Output:constructor is invoked
running safely..
it has two wheels 30
152
Rules for abstract class
153
Interface implementation using abstract
The abstract class can also be used to provide some implementation of the
interface. In such case, the end user may not be forced to override all the
methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
interface A{
void a(); void b(); void c(); void d(); }
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
154
Interface implementation using abstract
class M extends B
{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test{
public static void main(String args[]){
A a=new M(); a.a(); a.b(); a.c(); a.d(); }}
Output: I am a I am b I am c I am d
155
interface
Interface
What do you mean Interface
Example of Interface
Multiple inheritance by Interface
Why multiple inheritance is supported in Interface while it is
not supported in case of class.
Marker Interface
Nested Interface
156
interface
157
The java compiler converts methods of interface as public and
abstract, data members as public, final and static by default
158
Simple example of Interface
In this exmple, Printable interface have only one method, its implemenation
is provided in the A class.
interface printable
{ void print(); }
class A implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){ A obj = new A(); obj.print();
} }
Output:Hello
159
Multiple inheritance by interface
A class cannot extend two classes but it can implement two interfaces. For example:
interface printable{ void print(); }
interface Showable{ void show(); }
class A implements printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){ A obj = new A(); obj.print(); obj.show(); } }
Output: Hello Welcome
Multiple inheritance is not supported in case of class but it is supported in case
of interface, why? Ans - multiple inheritance is not supported in case of class. But
it is supported in case of interface because there is no ambiguity as implmentation
is provided by the implementation class.
160
interface
161
A class implements interface but One interface
extends another interface .
162
What is marker or tagged interface ?
163
Runtime Polymorphism
1. Runtime Polymorphism
2. Upcasting
3. Example of Runtime Polymorphism
4. Runtime Polymorphism with data members
Runtime polymorphism or dynamic method dispatch is a process in
which a call to an overridden method is resolved at runtime rather
than at 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.
164
Upcasting
Upcasting
When reference variable of Parent class refers to the object of Child class,
it is known as upcasting.
class A{}
class B extends A{}
A a=new B();//upcasting
165
Example of Runtime Polymorphism
In this example, we are creating two classes Bike and Splendar. Splendar class
extends Bike class and overrides its run() method. We are calling the run method
by the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, subclass method is invoked at
runtime. Since it is determined by the compiler, which method will be invoked at
runtime, so it is known as runtime polymorphism.
class Bike{ void run(){System.out.println("running");} }
class Splender extends Bike{ void run(){
System.out.println("running safely with 60km");}
public static void main(String args[]){ Bike b = new Splender();//upcasting
b.run(); } }
Output: running safely with 60km.
166
Runtime Polymorphism with data member
167
Runtime polymorphism can't be achieved by
data members
168
Static Binding and Dynamic Binding
Binding:
Connecting a method call to a method body is called binding.It can be of
two types:
static binding(early binding).
dynamic binding(late binding).
About type:
1) variables have a type
For example: int data=30; //Here data variable is a type of int.
2) References have a type
class Dog { public static void main(String args[]){ Dog d1;//Here d1 is a type of
Dog }}
169
Static Binding and Dynamic Binding
170
Static Binding
static binding
When type of the object is determined at compiled time(by the compiler),
it is known as static binding.
If there is any private,final or static method in a class,it is static binding.
Example of static binding:
class Dog{
private void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Dog d1=new Dog(); d1.eat(); } }
171
Dynamic Binding
Dynamic binding:
When type of the object is determined at run-time, it is known as dynamic
binding.
Example of dynamic binding:
class Animal{
void eat(){System.out.println("animal is eating...");} }
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Animal a=new Dog(); a.eat(); } } Output:dog is eating...
172
instanceof operator
class Simple{
public static void main(String args[]){
Simple s=new Simple();
System.out.println(s instanceof Simple);//true
}
}
Output: true
174
instanceof operator with a variable that
have null value
175
Downcasting with instanceof operator
176
downcasting with instanceof operator
177
Down casting without the use of instanceof
operator
Down casting can also be performed without the use of instanceof operator as
displayed in the following example:
class Animal { } class Dog extends Animal {
static void method(Animal a) {
Dog d=(Dog)a;//downcasting
System.out.println("ok downcasting performed"); }
public static void main (String [] args) {
Animal a=new Dog(); Dog.method(a); } }
Output:ok downcasting performed
Let's take closer look at this, actual object that is referred by a, is an object of Dog
class. So if we downcast it, it is fine. But what will happen if we write:
Animal a=new Animal();Dog.method(a);
178
Package
1. Package
2. Example of package
3. Accessing package
4. By import packagename.*
5. By import packagename.classname
6. By fully qualified name
7. Subpackage
179
Package
180
Package diagram
181
Example of Package
182
How to access package from another package?
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
fully qualified name.
If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
183
Example of package that import the
packagename.*
184
Example
If you import package.classname then only declared class of this package will be
accessible but not subpackages.
Example of package by import package.classname
//save by A.java
package pack; public class A{ public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack; import pack.A; class B{
public static void main(String args[]){
A obj = new A();
obj.msg(); } } Output:Hello
185
Example of package by import fully qualified name
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
//save by A.java
package pack; public class A{ public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg(); } } Output:Hello
186
Sequence of the program must be package
then import then class.
187
Example of subpackage
package com.
javatpoint.core;
class Simple{ public static void main(String args[]){ System.out.println("Hello
subpackage"); }}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackageNote:
If you import a package, all the classes and interface of that package will
be imported excluding the classes and interfaces of the subpackages.
Hence, you need to import the subpackage as well.
188
Access Modifiers
189
Types of Access modifier
private
default
protected
public
There are many non-access modifiers such as static, abstract,
synchronized, native, volatile, transient etc. Here, we will learn access
modifiers.
1) private
The private access modifier is accessible only within class.
190
Example of private access modifier
191
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that
class from outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");} }
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
} }
Note: A class cannot be private or protected except nested class.
192
default
2) default
If you don't use any modifier, it is treated as default modifier bydefault. The
default modifier is accessible only within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are
accessing the A class from outside its package, since A class is not public, so it
cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
193
Example of default
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}}
In the above example, the scope of class A and its method msg() is
default so it cannot be accessed from outside the package.
194
Protected
3) protected
The protected access modifier is accessible within package and outside the
package by only through inheritance. The protected access modifier can be
applied on the data member, method and constructor. It can't be applied on the
class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class
of pack package is public, so can be accessed from outside the package. But msg
method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance.
195
Example of protected
//save by A.java
package pack; public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B(); obj.msg(); } } Output:Hello
196
public
4) public
The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
} //save by B.java
package mypack;import pack.*; class B{ public static void main(String args[]){ A obj =
new A(); obj.msg(); }} Output:Hello
197
Encapsulation
Encapsulation is a process of wrapping code and data together into a single unit. It
is a way to achieve data hiding.
Simple example:
//save as Student.java
package mypack;
public class student{ private string name; public String getName(){
return name; }
public void setName(String name){ this.name=name } } package mypack;
class Test
public static void main(){ Student s=new Student(); s.setname("vijay");
System.out.println(s.getName()); } }
198
Object Class
The Object class is the super class of all the classes in java. The Object 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.
The Object class provides some common behaviours to all the objects such as
object can be compared, object can be cloned, object can be notified etc.
Methods of Object class
The Object class provides many methods. They are as follows:
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.
199
Object class Method
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 miliseconds, until another thread notifies (invokes notify() or
notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedExceptioncauses the
current thread to wait for the specified miliseconds 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.
200
clone() method (Object Cloning in Java)
201
Why use clone() method ?
The clone() saves the extra processing task for creating the exact copy of an
object. If we perform it by using the new keyword, it will take a lot of processing to
be performed that is why we use object cloning.
Example of clone() method (Object cloning)
class Student implements Cloneable{
int rollno; String name;
Student(int rollno,String name){
this.rollno=rollno; this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone(); }
202
Example of clone method
203
Array in Java
Array in Java
Normally, array is a collection of similar type of elements that have contigious
memory location.
In java, array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed elements in an
array.
Array is index based, first element of the array is stored at 0 index.
204
Advantage of Array
Advantage of Array
Code Optimization: It makes the code optimized, we can retrive or sort the data
easily.
Random access: We can get any data located at any index position.
Disadvantage of Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.
Types of Array
Two types of array. - Single Dimensional Array & Multidimensional Array
Single Dimensional Array
Syntax to Declare an Array in java
dataType[] arrayRefVar; (or) dataType []arrayRefVar; (or) dataType arrayRefVar[];
205
Instantiation of an Array in java
arrayRefVar=new datatype[size];
Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
class B{
public static void main(String args[]){
int a[]=new int[5]; //declaration and instantiation
a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]); }} Output: 10 20 70 40 50
206
Declaration, Instantiation and Initialization of Java
Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
class B{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]); }}
Output: 33 3 4 5
207
Passing Java Array in the method
We can pass the array in the method so that we can reuse the same logic on any
array. Let's see the simple example to get minimum number of an array using
method.
class B{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min);
} public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array in the method
}}
Output:3
208
Multidimensional array
Data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in java
dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];
Example to initantiate Multidimensional Array in java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5;
arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9;
209
Example of Multidimensional java array
210
What is class name of java array?
In java, array is an object. For array object, an proxy class is created whose name
can be obtained by getClass().getName() method on the object.
class B{
public static void main(String args[]){
int arr[]={4,4,5};
Class c=arr.getClass();
String name=c.getName(); System.out.println(name); } }}
Output:[I Copying an array
We can copy an array to another by the arraycopy method of System class.
Syntax of arraycopy method
public static void arraycopy( Object src, int srcPos,Object dest, int destPos, int length )
211
Example of arraycopy method
212
Call by Value in Java
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.
In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50; void change(int data){ data=data+100;//changes will be in the local
variable only }
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data); op.change(500);
System.out.println("after change "+op.data); } }
Output: before change 50 after change 50
213
Another Example of call by value in java
Advantage of OOPs
Naming Convention Object and class Method overloading
Constructor static keyword this keyword with 6
usage
Inheritance Aggregation Method Overriding
Covariant Return Type super keyword Instance Initializer block
final keyword Abstract class Interface
Runtime Polymorphism Static Binding Dynamic Binding
Package Access Modifiers Encapsulation
Object Cloning Downcasting with instanceof operator
215
Questions ?
216