Wednesday, 23 December 2015

Abstract class in Java

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
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.
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
In this example, Printable interface have only one method, its implementation is provided in the A class.
interface printable{  
void print();  
}  
  
class A implements printable{  
public void print(){System.out.println("Hello");}  
  
public static void main(String args[]){  
A obj = new A();  
obj.print();  
 }  
}  
Output:Hello

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.

To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .represents the current folder.

How to access package from another package?
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
fully qualified name.
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.*
//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: Sequence of the program must be package then import then 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 etc. Here, we will learn access modifiers.

1) private
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private 
members from outside the class, so there is compile time error.
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:
If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:
class A{  
private A(){}//private constructor  
  
void msg(){System.out.println("Hello java");}  
}  
  
public class Simple{  
 public static void main(String args[]){  
   A obj=new A();//Compile Time Error  
 }  
}  

2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, 
so it cannot be accessed from outside the package.
//save by A.java  
  
package pack;  
class A{  
  void msg(){System.out.println("Hello");}  
}  
//save by B.java  
  
package mypack;  
import pack.*;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();//Compile Time Error  
   obj.msg();//Compile Time Error  
  }  
}  
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

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
In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. 
But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.
//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
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
//save by A.java  
  
package pack;  
public class A{  
public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
  
package mypack;  
import pack.*;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
Output:Hello
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
Access Modifier
within class
within package
outside package by subclass only
outside package
Private
Y
N
N
N
Default
Y
Y
N
N
Protected
Y
Y
Y
N
Public
Y
Y
Y
Y

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();  
   }  
}  
The default modifier is more restrictive than protected. That is why there is compile time error.

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.

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


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, 07);  
        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