Solution:NIIT/GNIIT Sonugiri0032@gmail.com

Monday, October 19, 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:
  1. variable
  2. method
  3. 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
1.    final class Bike{}  
2.      
3.    class Honda extends Bike{  
4.      void run(){System.out.println("running safely with 100kmph");}  
5.        
6.      public static void main(String args[]){  
7.      Honda honda= new Honda();  
8.      honda.run();  
9.      }  
10. }  
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
  1. Abstract class (0 to 100%)
  2. 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.
1.    abstract class Bike{  
2.      abstract void run();  
3.    }  
4.      
5.    class Honda extends Bike{  
6.    void run(){System.out.println("running safely..");}  
7.      
8.    public static void main(String args[]){  
9.     Bike obj = new Honda();  
10.  obj.run();  
11. }  
12. }  
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.
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  
2.     abstract class Bike{  
3.       abstract void run();  
4.       void changeGear(){System.out.println("gear changed");}  
5.     }  
6.      
7.     class Honda extends Bike{  
8.     void run(){System.out.println("running safely..");}  
9.      
10.  public static void main(String args[]){  
11.   Bike obj = new Honda();  
12.   obj.run();  
13.   obj.changeGear();  
14.  }  
15. }  
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

In this example, Printable interface have only one method, its implementation is provided in the A class.
1.    interface printable{  
2.    void print();  
3.    }  
4.      
5.    class A implements printable{  
6.    public void print(){System.out.println("Hello");}  
7.      
8.    public static void main(String args[]){  
9.    A obj = new A();  
10. obj.print();  
11.  }  
12. }  
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.
1.    interface Printable{  
2.    void print();  
3.    }  
4.      
5.    interface Showable{  
6.    void show();  
7.    }  
8.      
9.    class A implements Printable,Showable{  
10.   
11. public void print(){System.out.println("Hello");}  
12. public void show(){System.out.println("Welcome");}  
13.   
14. public static void main(String args[]){  
15. A obj = new A();  
16. obj.print();  
17. obj.show();  
18.  }  
19. }  
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.
1.    //save as Simple.java  
2.      
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:
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.

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.
1.    import package.*;
2.    import package.classname;
3.    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.*

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: 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:
  1. private
  2. default
  3. protected
  4. 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.
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:
If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:
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. }  

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.
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. }  
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.
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
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.      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.
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.
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. }  
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
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


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


Share:

0 comments:

GNIITSOLUTION GNIIT SOLUTION. Powered by Blogger.

Translate

Blog Archive

Unordered List