Final Keyword In Java
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
1. 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
1. 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.
1. abstract class Shape{
2. abstract void draw();
3. }
4.
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class Circle extends Shape{
10. void draw(){System.out.println("drawing circle");}
11. }
12.
13. class Test{
14. public static void main(String args[]){
15. Shape s=new Circle();
16. //In real scenario, Object is provided through factory method
17. s.draw();
18. }
19. }
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.
1. //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
1. //example of abstract class having constructor, field and method
2. abstract class Bike
3. {
4. int limit=30;
5. Bike(){System.out.println("constructor is invoked");}
6. void getDetails(){System.out.println("it has two wheels");}
7. abstract void run();
8. }
9.
10. class Honda extends Bike{
11. void run(){System.out.println("running safely..");}
12.
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.getDetails();
17. System.out.println(obj.limit);
18. }
19. }
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
|
Simple example of package
The package keyword is used to create a package.
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. }
|
How to compile the Package (if not using IDE)
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. 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.*
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. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
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
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.A;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
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
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. class B{
5. public static void main(String args[]){
6. pack.A obj = new pack.A();//using fully qualified name
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
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. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
Output:Hello subpackage
|
How to send the class file to another directory or drive?
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:
|
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
|
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{}
|
How to put two public classes in a package?
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
|
What is static import feature of Java5?
|
What about package class?
Next TopicAccess Modifiers in java
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:
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
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
Role of Private Constructor:
1. class A{
2. private A(){}//private constructor
3.
4. void msg(){System.out.println("Hello java");}
5. }
6.
7. public class Simple{
8. public static void main(String args[]){
9. A obj=new A();//Compile Time Error
10. }
11. }
Note: A class cannot be private or protected except nested class.
2) default
Example of default access modifier
1. //save by A.java
2.
3. package pack;
4. class A{
5. void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();//Compile Time Error
9. obj.msg();//Compile Time Error
10. }
11. }
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
1. //save by A.java
2.
3. package pack;
4. public class A{
5. protected void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B extends A{
7. public static void main(String args[]){
8. B obj = new B();
9. obj.msg();
10. }
11. }
Output:Hello
4) public
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. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
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.
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
Next TopicEncapsulation in java
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.
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
Run By: java com.javatpoint.Test
Output: vijay
Next TopicObject class in java
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
Disadvantage of Array
Types of Array
There are two types of array.
Single Dimensional Array
Syntax to Declare an Array in java
1. dataType[] arrayRefVar; (or)
2. dataType []arrayRefVar; (or)
3. dataType arrayRefVar[];
Instantiation of an Array in java
1. 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.
1. class B{
2. public static void main(String args[]){
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. }}
Output: 10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
1. int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
1. class B{
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. }}
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.
1. class B{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
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 in the method
15.
16. }}
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
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in java
1. int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. class B{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
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. }}
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 B{
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. }}
Output:I
Copying an 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 ArrayCopyDemo {
2. public static void main(String[] args) {
3. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
4. 'i', 'n', 'a', 't', 'e', 'd' };
5. char[] copyTo = new char[7];
6.
7. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
8. System.out.println(new String(copyTo));
9. }
10. }
Output:caffein
Addition 2 matrices
Let's see a simple example that adds two matrices.
1. class AE{
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. }}
Output:2 6 8
6 8 10
Next TopicCall by value and Call by reference in Java
|
|
No comments:
Post a Comment