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, a final variable that have no
value it is called blank final variable or uninitialized final variable. It can
be initialized in the constructor only. The blank final variable can be static
also which will be initialized in the static block only. We will have detailed
learning of these. Let's first learn the basics of final keyword.

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();
}
}//end of class
Output:Compile Time Error
--------------------------------------------------------------------------
2) final method
If
you make any method as final, you cannot override it.
Example of final method
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
--------------------------------------------------------------------------
3) final class
If
you make any class as final, you cannot extend it.
Example of final class
final class Bike{}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
--------------------------------------------------------------------------
Abstract class in Java
A
class that is declared with abstract keyword, is known as abstract class.
Before learning abstract class, let's understand the abstraction first.
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
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
Abstract
class (0 to 100%)
Interface
(100%)
--------------------------------------------------------------------------
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{}
Example of abstract class that have
abstract method
In
this example, Bike the abstract class that contains only one abstract method
run. It implementation is provided by the Honda class.
abstract class Bike{
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();
}
}
Output:running safely..
--------------------------------------------------------------------------
Understanding
the real scenario of abstract class
In
this example, Shape is the abstract class, its implementation is provided by
the Rectangle and Circle classes. Mostly, we don't know about the
implementation class (i.e. hidden to the end user) and object of the
implementation class is provided by the factory method.
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.
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}
class Test{
public static void main(String args[]){
Shape s=new Circle();
//In real scenario, Object is provided through factory method
s.draw();
}
}
Output:drawing circle
--------------------------------------------------------------------------
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..
gear
changed
//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
Rule: If there is any abstract
method in a class, that class must be abstract.
|
Interface in Java
An interface is a blueprint of a class. It has
static constants and abstract methods.
The interface is a mechanism to achieve fully
abstraction in java. There
can be
only abstract methods in the interface. It is used to achieve fully
abstraction and
multiple inheritance in Java.
Interface also represents IS-A relationship.
It cannot be instantiated just like
abstract class.
Why use Interface?
There are mainly three reasons to use
interface. They are given below.
It is used to achieve fully abstraction.
By interface, we can support the
functionality of multiple inheritance.
It can be used to achieve loose coupling.
The java compiler adds public and abstract
keywords before the interface method
and public, static and final keywords
before data members.
In other words, Interface fields are
public, static and final bydefault, and methods are
public and abstract.
![]()
Understanding
relationship between classes and interfaces
As shown in the figure given below, a
class extends another class, an interface extends
another interface but a class implements an interface.
![]()
Simple example of Interface
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
Multiple inheritance in Java by
interface
If a class implements multiple
interfaces, or an interface extends multiple interfaces
i.e. known as
multiple inheritance.
![]()
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
Package in Java
A package is a group of similar types of
classes, interfaces and sub-packages.
Package 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 Package
Package is used to categorize the classes
and interfaces so that they can be easily maintained.
Package provids access protection.
Package removes naming collision.
![]()
Simple example of package
The package
keyword is used to create a
package.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to
compile the Package (if not using IDE)
If you are not using any IDE, you need to
follow the syntax given below:
javac -d directory javafilename
For example
javac -d . Simple.java
The -d switch specifies the destination
where to put the generated class file. You can
use any directory name like
/home (in case of Linux), d:/abc (in case of windows) etc.
If you want to
keep the package within the same directory, you can use . (dot).
--------------------------------------------------------------------------
How to
run the Package (if not using IDE)
You need to use fully qualified name e.g.
mypack.Simple etc to run the class.
--------------------------------------------------------------------------
Output:Welcome to
package
--------------------------------------------------------------------------
How to access package from another
package?
Using
packagename.*
Example of package that import the
packagename.*
//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
--------------------------------------------------------------------------
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
//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
--------------------------------------------------------------------------
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
//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
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
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
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
Output:Hello
subpackage
--------------------------------------------------------------------------
How to send the class file to
another directory or drive?
![]()
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To
Compile:
To
Run:
Another
way to run this program by -classpath switch of java:
Output:Welcome to
package
--------------------------------------------------------------------------
Ways
to load the class files or jar files
Temporary
By setting the classpath in the command
prompt
By -classpath switch
Permanent
By setting the classpath in the
environment variables
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.
//save as C.java otherwise Compilte Time Error
class A{}
class B{}
public class C{}
--------------------------------------------------------------------------
How
to put two public classes in a package?
//save as A.java
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}
--------------------------------------------------------------------------
What
is static import feature of Java5?
What
about package class?
Access Modifiers
There
are two types of modifiers in java: access modifier and non-access
modifier.
The access modifiers specifies accessibility (scope) of a
datamember, method, constructor
or class.
There
are 4 types of access modifiers:
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
Simple example of private access
modifier
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role
of Private Constructor:
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.
--------------------------------------------------------------------------
2) default
Example of default access modifier
//save by A.java
package pack;
class A{
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();//Compile Time Error
obj.msg();//Compile Time Error
}
}
--------------------------------------------------------------------------
3) protected
The protected
access modifier is accessible within package and outside the package
but through inheritance only.
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
//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
--------------------------------------------------------------------------
4) public
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
Understanding
all java access modifiers
Let's
understand the access modifiers by a simple table.
Applying
access modifier with method overriding
If you are overriding any
method, overridden method (i.e. declared in subclass)
must not be more
restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
Encapsulation in Java
Encapsulation is a process of
wrapping code and data together into a single unit
e.g. capsule i.e mixed of
several medicines.
We can create a fully
encapsulated class 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.
Java
Bean is the example of
fully encapsulated class.
Advantage
of Encapsulation
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.
//save as Student.java
package com.javatpoint;
public class Student{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name
}
}
//save as Test.java
package com.javatpoint;
class Test{
public static void main(String[] args){
Student s=new Student();
s.setname("vijay");
System.out.println(s.getName());
}
}
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output: vijay
Array in Java
Normally,
array is a collection of similar type of elements that have contiguous
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.
![]()
Advantage
of Array
Code
Optimization: It
makes the code optimized, we can retrieve 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
There
are 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[];
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
--------------------------------------------------------------------------
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
--------------------------------------------------------------------------
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
--------------------------------------------------------------------------
Multidimensional
array
In
such case, 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 instantiate 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;
Example of Multidimensional java array
Let's
see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
class B{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
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.
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
)
Example
of arraycopy method
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
Output:caffein
--------------------------------------------------------------------------
Addition 2
matrices
Let's
see a simple example that adds two matrices.
class AE{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Output:2 6 8
6 8
10
|








No comments:
Post a Comment