Java OOPs Concepts
Java OOPs Concepts
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of its parent
object i.e. known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convense the customer differently, to draw something e.g. shape or
rectangle etc.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different stuffs.
A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
Advantage of OOPs over Procedure-oriented programming language
1)OOPs makes development and maintenance easier whereas in Procedureoriented programming language it is not easy to manage if code grows as project
size grows.
2)OOPs provides data hiding whereas in Procedure-oriented programming
language a global data can be accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We
can provide the solution of real word problem if we are using the Object-Oriented
Programming language.
Name
Convention
class
name
interface
name
method
name
variable
name
package
name
An entity that has state and behavior is known as an object e.g. chair, bike, marker,
pen, table, car etc. It can be physical or logical (tangible and intangible). The
example of intangible object is banking system.
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 the ID is not visible to the external user. But,it is used internally by
the JVM to identify each object uniquely.
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 in Java
class <class_name>{
data member;
method;
}
Simple Example of Object and 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.
public class Student1 {
int id;
String name;
public static void main(String[] args) {
Student1 std=new Student1();
System.out.println(std.id);
System.out.println(std.name);
}
}Output:0
null
As you see in the above figure, 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.
Another Example of Object and Class
There is given another example that maintains the records of Rectangle class. Its
exaplanation is same as in the above Student class 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[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:
By new keyword
By newInstance() method
By clone() method
By factory method etc.
We will learn, these ways to create the object later.
Annonymous object
Annonymous simply means nameless. An object that have no reference is known
as annonymous object.
If you have to use an object only once, annonymous object is a good approach.
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
Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case of primitives.
1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
Let's see the example:
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
class Overloading1{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}
}
Output:main() method invoked
10
Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching data type is found. Let's
understand the concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float
or double. The short data type can be promoted to int,long,float or double. The char
datatype can be promoted to int,long,float or double and so on.
Example of Method Overloading with Type Promotion
class OverloadingCalculation1{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
Output:40
60
Example of Method Overloading with TypePromotion if matching found
If there are matching type arguments in the method, type promotion is not
performed.
class OverloadingCalculation2{
void sum(int a,int b){System.out.println("int arg method
invoked");}
void sum(long a,long b){System.out.println("long arg method
invoked");}
public static void main(String args[]){
OverloadingCalculation2 obj=new
OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Output:int arg method invoked
}
Output:Compile Time Error
Constructor in Java
1. Types of constructors
1. Default Constructor
2. 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
Constructor is a special type of method that is used to initialize the object.
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 constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of constructors
There are two types of constructors:
1. default constructor (no-arg constructor)
2. parameterized constructor
1) Default Constructor
A constructor that has no parameter is known as default constructor.
Syntax of default constructor:
1. <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
public class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output: Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a
default constructor.
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor.Here 0 and null values are provided by default
constructor.
Parameterized constructor
Output:111 Karan 0
222 Aryan 25
What is the difference between constructor and method ?
There are many differences between constructors and methods. They are given
below.
Constructor
Method
Constructor is used to initialize the state of an
Method is used to expose
object.
behaviour 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 Method is not provided by
if you don't have any constructor.
compiler in any case.
Constructor name must be same as the class
Method name may or may not be
name.
same as class name.
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.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s2){
id = s2.id;
name =s2.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output:111 Karan
111 Karan
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){
Student7 s=new Student7(234,"navneet");
s.display();
Thread t=new Thread();
System.out.println(t.currentThread());
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Output:
234 navneet
Thread[main,5,main]
111 Karan
111 Karan
static keyword
The static keyword is used in java mainly for memory management. We may
apply 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:
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.
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.
static property is shared to all objects.
Example of static variable
class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+"
"+Student8.college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
Output:1
2
3
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 Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
Student9.change();
s1.display();
s2.display();
s3.display();
}
}
3)static block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
class A2{
static{
System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Error: Main method not found in class com.syniverse.learning.other.A3, please define the
main method as:
public static void main(String[] args)
this keyword
1. this keyword
2. Usage of this keyword
1. to refer the current class instance variable
2. to invoke the current class constructor
3. to invoke the current class method
4. to pass as an argument in the method call
5. to pass as an argument in the constructor call
6. to return the current class instance
3. Proving this keyword
There can be a lot of usage of this keyword. In java, this is a reference variable
that refers to the current object.
Usage of this keyword
Here is given the 6 usage of this keyword.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
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 keyword can also be used to return the current class instance.
Suggestion:If you are beginner to java, lookup only two usage of this keyword.
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
below:
class Student10{
int id;
String name;
Student10(int id, String name) {
// TODO Auto-generated constructor stub
id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}
Output:0 null
0 null
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 Student11{
int id;
String name;
Student11(int id, String name) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(321,"Aryan");
s1.display();
s2.display();
}
}
Output
111 Karan
222 Aryan
class Student12{
int id;
String name;
Student12(int i,String n){
id = i;
name = n;
System.out.println(i+"constructor called"+n);
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student12 e1 = new Student12(111,"karan");
Student12 e2 = new Student12(222,"Aryan");
e1.display();
e2.display();
}
}
Output:111 Karan
222 Aryan
2) this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor
(constructor chaining). This approach is better if you have many constructors in the
class and want to reuse that constructor.
//Program of this() constructor call (constructor chaining)
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
Student13(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
}
void display(){System.out.println(id+" "+name);}
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. Let's see the example
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
System.out.println("method n() invoked");
this.m();//no need because compiler does it for you.
}
void p(){
System.out.println("method p()");
this.n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.m();
s1.p();
}
B b=new B(this);
b.display();
Output:10
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
example:
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 Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:Hello java
Proving this keyword
Let's prove that this keyword refers to the current class instance variable. In this
program, we are printing the reference variable and this, output of both variables
are same.
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
Output:A5@22b3ea59
A5@22b3ea59
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in java in case of class?
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?
For Method Overriding (So Runtime Polymorphism).
For Code Reusability.
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.
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A Employee.It
means that Programmer is a type of Employee.
class Employee{
int salary=4000;
}
public class Programmer extends Employee {
int bonus=1000;
public static void main(String[] args) {
In the above example, Programmer object can access the field of own class as well
as of Employee class i.e. code reusability.
Types of Inheritance
On the basis of class, there can be three types of inheritance: single, multilevel and
hierarchical in java.
In java programming, multiple and hybrid inheritance is supported through
interface only. We will learn about interfaces later.
In this example, we have created the reference of Operation class in the Circle
class.
class Operation{
int square(int side){
return side*side;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates
the method call).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
Output:78.5
When use Aggregation?
void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+"
"+address.country);
}
public static void main(String[] args) {
Address1 address1=new Address1("gzb","UP","india");
Address1 address2=new Address1("gno","UP","india");
Emp e=new Emp(111,"varun",address1);
Emp e2=new Emp(112,"arun",address2);
e.display();
e2.display();
}
}
Output:111
gzb
112
gno
varun
UP india
arun
UP india
}
Output:Vehicle is running
package com.syniverse.learning.other;
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
} }
package com.syniverse.learning.other;
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?
There are three basic differences between the method overloading and method
overriding. They are as follows:
Method Overloading
1) Method overloading is used
to increase the readability of the
program.
2) method overloading is
performed within a class.
3) In case of method
overloading parameter must be
different.
Method Overriding
Method overriding is used to provide the specific
implementation of the method that is already
provided by its super class.
Method overriding occurs in two classes that have
IS-A relationship.
In case of method overriding parameter must be
same.
}
}
Output:welcome to covariant return type
As you can see in the above example, the return type of the get() method of Q class
is Q but the return type of the get() method of B1 class is B1. Both methods have
different return type but it is method overriding. This is known as covariant return
type.
How does covariant overriding method work?
Java 5.0 permits covariant overriding: an overriding method may have a result type
that is a subtype of the method it overrides.
class Z {
int x = 5;
}
class Y extends Z {
int x = 6;
}
class CovariantObj {
public Z getObject() {
System.out.println("In Z");
return new Z();
}
}
class SubCovariantObj extends CovariantObj {
public Y getObject() {
System.out.println("In Y");
return new Y();
}
public static void main(String[] args) {
CovariantObj c = new SubCovariantObj();
System.out.println(c.getObject().x);
}
}
The output is
In Y
5
=======================================================
Why the output of above code is 5 after printing "In Y"? The c.getObject() returns an
instance of Y class.
To make overriding works properly for covariant overriding case, Java compiler inserts
asynthetic bridge method that is Z getObject() method into the SubCovariantObj class.
The bridge method only is encoded directly in JVM byte code. For example, the JVM
byte code is similar to the following code:
super keyword
The super 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 super Keyword
Output:100
In the above example Vehicle and Bike both class have a common property speed.
Instance variable of current class is referred by instance bydefault, but I have to
refer parent class instance variable that is why we use super keyword to distinguish
between parent class instance variable and current class instance variable.
Solution by super keyword
package com.syniverse.learning.other;
class Vehicles{
int speed=50;
}
class Bike3 extends Vehicles{
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Bike
}
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
Output:50
2) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor as given
below:
package com.syniverse.learning.other;
class Vehicles{
Vehicles(){System.out.println("Vehicle is created");}
}
class Bike5 extends Vehicles{
Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
}
}
Output:Vehicle is created
Bike is created
super() is added in each class constructor automatically by compiler.
Output:Vehicle is created
10
3) super can be used to invoke parent class method.
The super keyword can also be used to invoke parent class method. It should be
used in case subclass contains the same method as parent class as in the example
given below:
class Person{
void message(){System.out.println("welcome");}
}
class Student16 extends Person{
void message(){System.out.println("welcome to java");}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student16 s=new Student16();
s.display();
}
}
Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if
we call message() method from Student class, it will call the message() method of
Student class not of Person class because priority is given to local.
In case there is no method in subclass as parent, there is no need to use super. In
the example given below message() method is invoked from Student class but
Student class does not have message() method, so you can directly call message()
method.
Program in case super is not required
class Person{
void message(){System.out.println("welcome");}
}
class Student17 extends Person{
void display(){
message();//will invoke parent class message() method
}
public static void main(String args[]){
Student17 s=new Student17();
s.display();
}
}
Output:welcome
Instance initializer block:
1. Instance initializer block
2. Example of Instance initializer block
3. What is invoked firstly instance initializer block or constructor?
4. Rules for instance initializer block
5. Program of instance initializer block that is invoked after super()
Instance Initializer block is used to initialize the instance data member. It run
each time when object of the class is created.
The initialization of the instance variable can be directly but there can be
performed extra operations while initializing the instance variable in the instance
initializer block.
Que) What is the use of instance initializer block while we can directly assign
a value in instance data member? For example:
1. class Bike{
2.
3. }
int speed=100;
Test it Now
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block
package com.syniverse.learning.other;
class Bike8{
int speed;
Bike8(){
System.out.println("constructor is invoked");
}
{
System.out.println("instance initializer block invoked");
}
Test it Now
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
In the above example, it seems that instance initializer block is firstly invoked but
NO. Instance intializer block is invoked at the time of object creation. The java
compiler copies the instance initializer block in the constructor after the first
statement super(). So firstly, constructor is invoked. Let's understand it by the
figure given below:
Note: The java compiler copies the code of instance initializer block in every
constructor.
Test it Now
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
Another example of instance block
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B3 extends A{
B3(){
super();
System.out.println("child class constructor invoked");
}
B3(int a){
super();
System.out.println("child class constructor invoked "+a);
}
{System.out.println("instance initializer block is invoked");}
public static void main(String args[]){
B3 b1=new B3();
B3 b2=new B3(10);
}
}
will be initialized in the static block only. Let's first learn the basics of final
keyword.
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 Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output:running...
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank
final variable.
If you want to create a variable that is initialized at the time of creating object and
once initialized may not be changed, it is useful. For example PAN CARD number
of an employee.
It can be initialized only in constructor.
Example of blank final variable
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
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();
}
}
Output:70
static blank final variable
A static final variable that is not initialized at the time of declaration is known as
static blank final variable. It can be initialized only in static block.
Example of static blank final variable
class A{
static final int data;//static blank final variable
static{
data=50;
}
public static void main(String args[]){
System.out.println(A.data);
}
}
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it. The final
local variable n cannot be assigned. It must be blank and not using a
compound assignment
package com.syniverse.learning.other;
class Bike11{
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[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
Output:Compile Time Error
Q) Can we declare a constructor final?
No, because constructor is never inherited.
Runtime Polymorphism in Java
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 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.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is
known as upcasting. For example:
package com.syniverse.learning.other;
class AA{
}
class Bee extends AA {
AA aa=new Bee();//upcasting
}
}
}
Output:running safely with 60km.
Real example of Java Runtime Polymorphism
Consider a scenario, Bank is a class that provides method to get the rate of interest.
But, rate of interest may differ according to banks. For example, SBI, ICICI and
AXIS banks could provide 8%, 7% and 9% rate of interest.
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Runtime Polymorphism with data member
Method is overridden not the datamembers, so runtime polymorphism can't be
achieved by data members.
In the example given below, both the classes have a datamember speedlimit, we
are accessing the datamember by the reference variable of Parent class which
refers to the subclass object. Since we are accessing the datamember which is not
overridden, hence it will access the datamember of Parent class always.
Rule: Runtime polymorphism can't be achieved by data members.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}
Output:90
Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel
inheritance.
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Output: eating
eating fruits
drinking Milk
Try for Output
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
}
class BabyDog1 extends Dog{
public static void main(String args[]){
Animal a=new BabyDog1();
a.eat();
}}
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is
invoked.
Static Binding and Dynamic Binding
class Animal{}
class Dog extends Animal{
public static void main(String args[]){
Dog d1=new Dog();
}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.
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, there 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();
}
}
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...");}
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because
the instance of Dog is also an instance of Animal.So compiler doesn't know its
type, only its base type.
Java instanceof
1. java instanceof
2. Example of instanceof operator
3. Applying the instanceof operator with a variable the have null value
4. Downcasting with instanceof operator
5. Downcasting without instanceof 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
Let's see the simple example of instance operator where it tests the current class.
package com.syniverse.learning.other;
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
Object o=new Object();
System.out.println(s instanceof Simple1);//true
System.out.println(o instanceof Object);
}
}
Output:true
true
An object of subclass type is also a type of parent class. For example, if Dog
extends Animal then object of Dog can be referred by either Dog or Animal class.
Another example of java instanceof operator
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
}
}
Output:true
class Animal { }
class Dog4 extends Animal {
static void method(Animal a) {
Dog4 d=(Dog4)a;//downcasting
System.out.println("ok downcasting performed");
}
public static void main (String [] args) {
Animal a=new Dog4();
Dog4.method(a);
}
}
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:
interface Printable{}
class A implements Printable{
public void a(){System.out.println("a method");}
}
class B implements Printable{
public void b(){System.out.println("b method");}
}
class Call{
void invoke(Printable p){//upcasting
if(p instanceof A){
A a=(A)p;//Downcasting
a.a();
}
if(p instanceof B){
B b=(B)p;//Downcasting
b.b();
}
}
}//end of Call class
class Test4{
public static void main(String args[]){
Printable p=new B();
Call c=new Call();
c.invoke(p);
}
}
Output: b method
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It
can have abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
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.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
abstract method
A method that is declared as abstract and does not have implementation is known
as abstract method.
Example abstract method
1. abstract void printStatus();//no body and abstract
A factory method is the method that returns the instance of the class. We will
learn about the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
File: TestAbstraction1.java
package com.syniverse.learning.other;
abstract class Shape1{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e.
unknown by end user
class Rectangle1 extends Shape1{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape1{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape1 s=new Circle1();//In real scenario, object is provided
through method e.g. getShape() method
s.draw();
}
}
Output:
drawing circle
Another example of abstract class in java
File: TestBank.java
abstract class Bank{
obj.run();
obj.changeGear();
}
}
Output:
bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
Test it Now
compile time error
Rule: If you are extending any abstract class that has abstract method, you
must either provide the implementation of the method or make this class
abstract.
}
abstract class B implements Aa{
public void c(){System.out.println("I am C");}
}
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 Test5{
public static void main(String args[]){
Aa a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:I
I
I
I
am
am
am
am
a
b
C
d
Interface in Java
1. Interface
2. Example of Interface
3. Multiple inheritance by Interface
4. Why multiple inheritance is supported in Interface while it is not supported
in case of class.
5. Marker Interface
6. Nested Interface
An interface in java is a blueprint of a class. It has static constants and abstract
methods only.
package com.syniverse.learning.other;
interface Printable1{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable1,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello
Welcome
Q) Multiple inheritance is not supported through class in java but it is
possible by interface, why?
interface Printable{
void print();
}
interface Showable{
void print();
}
class testinterface1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
testinterface1 obj = new testinterface1();
obj.print();
}
}
Hello
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class testinterface1, so there is
no ambiguity.
Interface inheritance
A class implements interface but one interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
Output
Hello
Welcome
}
Java Package
1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. -classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10.Package class
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.
package com.syniverse.learning.other;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
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.
Example of package that import the packagename.*
1. //save by A.java
2.
3. package pack;
4. public class A{
5.
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7.
8.
9.
obj.msg();
10. }
11.}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5.
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.A;
5.
6. class B{
7.
8.
9.
obj.msg();
10. }
11.}
Output:Hello
3) Using 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.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
Example of package by import fully qualified name
1. //save by A.java
2.
3. package pack;
4. public class A{
5.
6. }
1. //save by B.java
2.
3. package mypack;
4. class B{
5.
6.
7.
obj.msg();
8.
9. }
Output:Hello
Note: If you import a package, subpackages will not be imported.
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.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These
classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation, Socket and ServerSocket classes are for networking etc
and so on. So, Sun has subcategorized the java package into subpackages such as
lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
The standard of defining package is domain.company.package e.g.
com.javatpoint.bean or org.sssit.dao.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3.
4.
System.out.println("Hello subpackage");
5.
6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage
How to send the class file to another directory or drive?
There is a scenario, I want to put the class file of A.java source file in classes
folder of c: drive. For example:
1. //save as Simple.java
2.
3. package mypack;
4. public class Simple{
5. public static void main(String args[]){
6.
System.out.println("Welcome to package");
7.
8. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package
Ways to load the class files or jar files
There are two ways to load the class files temporary and permanent.
Temporary
o By setting the classpath in the command prompt
o By -classpath switch
Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying
the jar file in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be
saved by the public class name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
A obj=new A();
9.
void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5.
6.
7.
8.
9. }
In the above example, the scope of class A and its method msg() is default so it
cannot be accessed from outside the package.
7.
8.
obj.msg();
9.
10.}
Output:Hello
4) public access modifier
The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
Example of public access modifier
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7.
8.
9.
obj.msg();
10. }
11.}
Output:Hello
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
Access
Modifier
Private
Default
Protected
Public
within
class
Y
Y
Y
Y
within
package
N
Y
Y
Y
outside package by
subclass only
N
N
Y
Y
outside
package
N
N
N
Y
9.
obj.msg();
10. }
11.}
The default modifier is more restrictive than protected. That is why there is
compile time error.
Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a
single unit, for example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java by making all the data members of
the class private. Now we can use setter and getter methods to set and get the data
in it.
The Java Bean class is the example of fully encapsulated class.
Advantage of Encapsulation in java
By providing only setter or getter method, you can make the class read-only or
write-only.
It provides you the control over the data. Suppose you want to set the value of id
i.e. greater than 100 only, you can write the logic inside the setter method.
Simple example of encapsulation in java
Let's see the simple example of encapsulation that has only one field with its setter
and getter methods.
1. //save as Student.java
2. package com.javatpoint;
3. public class Student{
4. private String name;
5.
6. public String getName(){
7. return name;
8. }
9. public void setName(String name){
10.this.name=name
11.}
12.}
1. //save as Test.java
2. package com.javatpoint;
3. class Test{
4. public static void main(String[] args){
5. Student s=new Student();
6. s.setname("vijay");
7. System.out.println(s.getName());
8. }
9. }
Compile By: javac -d . Test.java
Method
Description
returns the Class class object of this
public final ClassgetClass()
object. The Class class can further be
used to get the metadata of this class.
returns the hashcode number for this
public int hashCode()
object.
public boolean equals(Object obj)
compares the given object to this object.
protected Object clone() throws
creates and returns the exact copy
CloneNotSupportedException
(clone) of this object.
returns the string representation of this
public String toString()
object.
wakes up single thread, waiting on this
public final void notify()
object's monitor.
wakes up all the threads, waiting on this
public final void notifyAll()
object's monitor.
causes the current thread to wait for the
public final void wait(long
specified milliseconds, until another
timeout)throws InterruptedException thread notifies (invokes notify() or
notifyAll() method).
causes the current thread to wait for the
public final void wait(long timeout,int specified miliseconds and nanoseconds,
nanos)throws InterruptedException until another thread notifies (invokes
notify() or notifyAll() method).
causes the current thread to wait, until
public final void wait()throws
another thread notifies (invokes notify()
InterruptedException
or notifyAll() method).
protected void finalize()throws
is invoked by the garbage collector
Throwable
before object is being garbage collected.
We will have the detailed learning of these methods in next chapters.
Object Cloning in Java
4.
5. Student18(int rollno,String name){
6. this.rollno=rollno;
7. this.name=name;
8. }
9.
10.public Object clone()throws CloneNotSupportedException{
11.return super.clone();
12.}
13.
14.public static void main(String args[]){
15.try{
16.Student18 s1=new Student18(101,"amit");
17.
18.Student18 s2=(Student18)s1.clone();
19.
20.System.out.println(s1.rollno+" "+s1.name);
21.System.out.println(s2.rollno+" "+s2.name);
22.
23.}catch(CloneNotSupportedException c){}
24.
25.}
26.}
Test it Now
Output:101 amit
101 amit
download the example of object cloning
As you can see in the above example, both reference variables have the same
value. Thus, the clone() copies the values of an object to another. So we don't need
to write explicit code to copy the value of an object to another.
If we create another object by new keyword and assign the values of another object
to this one, it will require a lot of processing on this object. So to save the extra
processing task we use clone() method.
Java Array
Normally, array is a collection of similar type of elements that have contiguous
memory location.
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 set of elements
in a java array.
Array in java is index based, first element of the array is stored at 0 index.
3.
4. int a[]=new int[5];//declaration and instantiation
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11.//printing array
12.for(int i=0;i<a.length;i++)//length is the property of array
13.System.out.println(a[i]);
14.
15.}}
Test it Now
Output: 10
20
70
40
50
1. class Testarray1{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10.}}
Test it Now
Output:33
3
4
5
5. if(min>arr[i])
6.
min=arr[i];
7.
8. System.out.println(min);
9. }
10.
11.public static void main(String args[]){
12.
13.int a[]={33,3,4,5};
14.min(a);//passing array to method
15.
16.}}
Test it Now
Output:3
Multidimensional array in java
In such case, data is stored in row and column based index (also known as matrix
form).
Syntax to Declare Multidimensional Array in java
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13.}
14.
15.}}
Test it Now
Output:1 2 3
2 4 5
4 4 5
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.
1. class Testarray4{
2. public static void main(String args[]){
3.
4. int arr[]={4,4,5};
5.
6. Class c=arr.getClass();
7. String name=c.getName();
8.
9. System.out.println(name);
10.
11.}}
Test it Now
Output:I
Copying a java array
We can copy an array to another by the arraycopy method of System class.
Syntax of arraycopy method
1. public static void arraycopy(
2. Object src, int srcPos,Object dest, int destPos, int length
3. )
Example of arraycopy method
1. class TestArrayCopyDemo {
2.
3.
4.
5.
6.
7.
8.
System.out.println(new String(copyTo));
9.
10.}
Test it Now
Output:caffein
Addition of 2 matrices in java
Let's see a simple example that adds two matrices.
1. class Testarray5{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
7. //creating another matrix to store the sum of two matrices
8. int c[][]=new int[2][3];
9.
10.//adding and printing addition of 2 matrices
11.for(int i=0;i<2;i++){
12.for(int j=0;j<3;j++){
13.c[i][j]=a[i][j]+b[i][j];
14.System.out.print(c[i][j]+" ");
15.}
16.System.out.println();//new line
17.}
18.
19.}}
Test it Now
Output:2 6 8
6 8 10
Call by Value and Call by Reference 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.
Example of call by value in java
In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9.
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16.}
download this example
Output:before change 50
after change 50
Another Example of call by value in java
In case of call by reference original value is changed if we made changes in the
called method. If we pass object in place of any primitive value, original value will
be changed. In this example we are passing object as a value. Let's take a simple
example:
1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
1. class B{
2. strictfp abstract void m();//Illegal combination of modifiers
3. }
1. class B{
2. strictfp int data=10;//modifier strictfp not allowed here
3. }
1. class B{
2. strictfp B(){}//modifier strictfp not allowed here
3. }
Creating API Document | javadoc tool
We can create document api in java by the help of javadoc tool. In the java file, we
must use the documentation comment /**... */ to post information for the class,
method, constructor, fields etc.
Let's see the simple class that contains documentation comment.
1. package com.abc;
2. /** This class is a user-defined class that contains one methods cube.*/
3. public class M{
4.
5. /** The cube method prints cube of the given number */
6. public static void cube(int n){System.out.println(n*n*n);}
7. }
To create the document API, you need to use the javadoc tool followed by java file
name. There is no need to compile the javafile.