Monday, 14 December 2015

WHAT IS AN INTERFACE AND WHAT ARE ITS USES IN JAVA..??



INTRODUCTION:

       Hey friends.. Welcome Back.. In this post we are going to look at the Interface and the reasons for us to use the Interface In the java programs...

WHAT IS AN INTERFACE..??

 

     
 Consider your sweet home.. Won’t we like to be well organized ..?? Like in an orderly manner.. well suited for our daily life..??

      When we are in a hurry to set out of home.. we automatically pick up the routine things from the place we have allocated for it..!! For example.. wallet must be in the cupboard and shoes mustn’t be thrown some where else. We expect it to be in shoe rack.. !!

          Well .. this organized things makes life easier.. We keep the things we use in a routine manner in a some where accessible place and rarely accessible things in some where inside our home..!! Don’t we..??
Of course.. we do..!!

       Ok.. now..what is the connection between this and the Interface..??

       Well.. in INTERFACE we declare the methods and variables we are going to use it very often.. so that it need not be declared in each and every class.. !!
Sounds technical ..??

      Don’t worry.. lemme show you an example..

     Class Guitar
      {
         void play ( )
           {
              System.out.println(“I am playing guitar”);
          }
         public static void main(String args[])
          {
            Guitar g= new Guitar( );
             g.play();
         }

         Let us create another class and name it as violin
        Class violin
        {
          void play ( )
           {
             System.out.println(“I am playing violin”);
          }
        public static void main(String args[])
         {
           Violin c= new Violin( );
          c.play();
        }
    }

      Now imagine we are supposed to create the play method in about 10 classes . We have to manage it too !! So, now comes the argument

       JVM yells at the developer.. .

        JVM :  Hey man .. can’t you declare the methods you wish to use in an organized place so that I will implement  the methods automatically in all the class..??

       DEVELOPER : Oh.. Is it..?? But how will you know for which class you got to implement the methods that I have declared in some ORGANISED PLACE ..??

       JVM : Hmm… Good question.. Let me explain you my dear..

        We the machine, call the organized place as an INTERFACE.. where we let you ie. The developers put the stuffs you wish to see in many class.

      Then we usually will implement the methods , variables that have been declared in INTERFACE (organized place ) for the class that implements INTERFACE..!!

        DEVELOPER:  Oh.. man you are confusing..!! What are you trying to say ??  In short ..  the stuffs we regularly use will be inside the INTERFACE and which ever class implements INTERFACE , for that particular class, you will implement the variables and methods that is inside INTERFACE .. !! Am I right ??

     JVM  : Well said developer.. You learn how to use it.. Then you will understand the importance of using it.

   DEVELOPER :  Ok.. dude.. thanks for the explanation.. !! I am seriously glad to have you by my side..

         So, story stops here.. let’s jump to the example and see for better understanding..

   STEP 1:

        Create an interface by right clicking the package and select create an INTERFACE

       public interface stuffs
          {
          void play( );
          }

   STEP 2:

       Create a class Guitar and let that class implement the interface

       Class Guitar implements stuffs
        {
           void play( )
             {
               System.out.println(“I am playing guitar “);
           }
      }

      STEP 3:

           Create a class Violin and let that class implement the same interface

       Class Violin implements stuffs
        {
            void play( )
              {
                 System.out.println(“I am playing violin “);
             }
       }

     Class MainClass
        {
             public static void main(String args[] )
                {
                  Guitar g = new Guitar( );
                  g.play ( );
                  Violin v = new Violin( );
                 v.play( );
              }

OUTPUT:

     I am playing guitar
     I am playing violin

EXPLANATION:

         Now .. wow.. !! What we have done here..?? we have just created an interface and inside that interface we are declaring the method “play “ .

        Note: The method that is declared inside the INTERFACE must be proceeded with a semicolon.
Else it will throw an error and We are not supposed to create any method / variable definition inside the interface

          After creating an interface , we are creating classes and letting the class to implement the interface . So that class which implements the interface must implement all the methods and variables that it declared inside the interface, in this case, the play ( ) method.

IMPORTANT POINTS ABOUT INTERFACE :

          A class can implement more than one interface. Consider if the first interface has the method play and the second interface has the method pause then the class which implements these 2 interface must implement the methods play and pause for sure.

         INTERFACE won’t work unless IMPLEMENTS keyword is used in the class
Eg. Class Classname IMPLEMENTS interfacename

         Be it the method or the variable.. Which ever stuff is declared inside the interface must be proceeded with a semicolon.

     Eg. Interface sample
        {
           void samplemethod ( ) ;
           int  a ;
        }

      Apart from the implemented methods/ variables from the interface, a class can have normal methods/ variables too.

        All the methods that is declared within an interface is by default public and abstract.

        Any variable that is declared inside the interface is by default public,static and final

        We are not supposed to declare variable inside the interface as private or protected.

        We can’t declare the method inside the  interface as static, private or protected.

        If you don’t provide any access specifier by default it is public.

       We can’t declare constructors within an interface

        We can’t create any CONCRETE METHODS inside an interface . In short, a method with full definition is called as CONCRETE METHODS

      Eg . void add ( )
        {
           int a= 9;
           int b= 9;
           int sum = a + b;
       }

      This add ( ) is the CONCRETE METHOD whereas if we say void add( ); alone then it is method declaration.

        So we can’t use concrete method inside an interface

           Interface contains ABSTARCT METHODS. The method declaration inside the interface is called abstract methods and the methods with its full definition is called Concrete Methods.

          We all know a class can EXTEND another class. ie during inheritance. If you want to know about inheritance please refer this link Inheritance in JAVA

         A class can extend a class.. and similarly an interface can extend another interface. When it does so, 

           All the methods in both the interface must be available in the class that implements it.

           A class can implement an interface but an interface cannot implement a class.

           We cannot execute the interface alone .

    USES OF INTERFACE :

           Interface allows us to implement common behavior in different classes. The implementation can be entirely different.We saw in the above example, when a class implemented a method play ( ) , it was printing something and other class printed some other. So We can have different implementation.

        WHY INTERFACE CAME TO BEING ..??

           Well.. JAVA doesn’t support MULTIPLE INHERITANCE ..

            When a child has multiple parents its multiple inheritance. Since this feature isn’t there in JAVA.. INHERITANCE came to being to fulfill this.

            INTERFACE does the same job.. !! A class can implement more than one interface.
EXAMPLE:

     public interface dad
       {
          void sweet( );
      }
    public interface mum
      {
      void caring ( );
     }
    Class child implements dad , mum
       {
         void sweet ( )
             {
                 System.out.println(“I am sweet “);
            }
       void caring ( )
          {
             System.out.println(“I am caring”);
          }
        void childmethod( )
          {
              System.out.println(“I am not implemented method .. I am the method from child class”);
          }
     public static void main(String args[] )
        {
         Child c = new Child ( );
         c.sweet( );
         c.caring();
         c.childmethod();
      }

OUTPUT:

I am sweet
I am caring
I am not implemented method .. I am the method from child class

EXPLANATION:

           As you can see, there is a single class child that is implementing two interface dad and mum and all the method that is present inside the interface must be implemented and even the child class is having its own method too..!! 
            So , in short multiple inheritance is satisfied by means of INTERFACE.

CONCLUSION:

       So, folks.. thanks for reading this post.. Raise your collars and clap your hands if you have understood this concepts better.. !! Feel free to drop your comments below. Request for the post you wish to learn is highly welcomed. Hit like button and help me post more. Thanks and have a great day ahead J

WHAT IS AN ABSTRACT CLASS AND WHY DO WE USE THAT IN JAVA..??



INTRODUCTION:

      Hey folks.. In this post we are going to look about abstract class and its uses in java. Let’s jump to the post.

ABSTRACT CLASS IN JAVA:

   Abstract class is similar to interface . If you want to know about interface, have a look at this post Interface in java

   The reason we use this abstract class is that ,

       When we create an abstract class, the class will have the method declarations ie. We will say that we are going to use this method in some other child classes . We won’t provide an implementation for the abstract methods in the abstract classes.

      The class which has an “ABSTRACT” keyword is called as “abstract class”.

     All the member functions inside the abstract class must also be proceeded with “abstract “ keyword.

EXAMPLE:

abstract class AbstExample
    {
       abstract void add( ); 
       abstract void sub( );
   }

Class sum extends AbstExample
    {

     void add( )
      {
        int a= 8;
        int b=9;
        int sumvar = a +b;
      System.out.println(“the sum is “ + sumvar ) ;
    }
      void sub( )
     {
        int a = 8;
        int b = 6;
        int diffvar = a –b;
        System.out.println(“the diff is “ +diffvar );
     }

  public static void main(String args[] )
     {
      Sum s = new sum();
      s.add( );
      s.sub ( );
    }

OUTPUT:

   the sum is 17
   the diff is 2

EXPLANATION:

      As I said above.. the abstract class just contains declaration and actual method definition is given in the class that extends the abstract class.

     But Abstract class is similar to interface . The  main difference is, a class can extend only one abstract class but in interface , a class can implement more than one interface class.

IMPORTANT POINTS ABOUT ABSTRACT CLASS :

       An abstract class can have CONSTRUCTORS inside it.

      An abstract class cannot be instantiated .. meaning the abstract class cannot be invoked separately using “new”keyword  but WE CAN INVOKE THE ABSTRACT class if it has “PUBLIC STATIC VOID MAIN “ inside it.

      An abstract class is extended by another class using “EXTENDS” keyword , whereas in INTERFACE we will use “IMPLEMENTS “ keyword

      We can declare the member of abstract class as PRIVATE, DEFAULT, PROTECTED OR PUBLIC . It can also be static but whereas in INTERFACE , we cannot have private or protected methods. Interface methods cannot be static too. It is by default “public”.

        In abstract class we can have concrete methods along with abstract methods..


EXAMPLE:

   abstract class abs
   {
      abstract void add( ); // abstract method
      public void sub( )  // concrete method
        {
         int sub =9 -8;
         System.out.println(“the sub is “ +sub );
        }
    }

        So as shown above, the abstract class can have both abstract method as well as concrete method. A method with full implementation is called as Concrete method . An interface cannot have concrete method inside it.

     Abstract class can have non final and non static variables but wheras in interface, variables declared are always static and final.

WHEN TO USE INTERFACE AND WHEN TO USE ABSTRACT CLASS ?
 



 
        If you have a class that needs one or more abstracted class ( INTERFACE OR ABSTRACT CLASS ) to be extended or implemented then go for INTERFACE as interface will let the child class to implement one or more class but,

        If you don’t want more than one class to be extended then go for ABSTRACT CLASS.

CONCLUSION :

       So.. that’s it for this post. Please hit like button and drop your comments below . Request for the post you wish to learn is welcomed . Support me to post more .. !! Stay tuned for more post . !! Thanks for reading .. Have a peaceful day ahead :)




HOW TO GET INPUT FROM THE USER IN JAVA..??

       
 INTRODUCTION:

         Heii friends..In this tutorial I am going to show you to how to get the input from the user.
 

WAYS TO GET THE INPUT FROM THE USER..

         There are 2 ways to get the input from the user. Let’s discuss one by one..

USING DATAINPUTSTREAM :

       Using DataInputStream is one way to get the input. I will give a step by step explanation of using DataInputStream

        Initially every Java Program will start with a class..

        Class Happy
        {

        }

       And every class will have a public static void main(String args[])

So the actual syntax will be,

   Class Happy
     {
          Public static void main(String args)
              {

             }
     }

      So, our actual target is to get the input from the user using DataInputStream.

     EXAMPLE:

        Class Happy
         {
             public static void main(String args)
                {
                    int a, b;  --------------------------------------- >>>> 1
                    DataInputStream dis = new DataInputStream(System.in );
                     a= Integer.ParseInt(dis.readLine() );
                     System.out.println(“The value user printed is” +a);
                }
          }

    EXPLANATION:

           1 ------ > Here we are declaring 2 variables of Integer data type.

          Then we are using DataInputStream , creating an object for it and the above is the actual syntax for using it.

        Then  comes the code a = Integer.ParseInt(dis.readLine() );

        “a” is the variable which holds the value the user enters .

         But what’s the code Integer.ParseInt(dis.readLine() ); doing there..?

        Fine.. compiler usually will consider all the inputs we enter in a String format. If we provide the Integer value as an Input then Compiler will get baffled and will scold developers for this awful code..!!
         So what we have planned to do is, we are converting the “Integer input to String format “ and we are passing to the Compiler and so the code , Integer.ParseInt(we are parsing to the String format from the Integer format)

    OUTPUT:

      So what the output will be?? Can you guess??

      Itss Compile time error..

      But Why..??

      Because when we use DataInputStream , we must either surround the code with try/ catch or add Throws declaration in main method. The compiler is expecting to protect the code when an exception occurs.

       So, after adding desired things the output actually will be,

      Class Happy
      {
          public static void main(String args) throws IOException
           {
              int a;
              DataInputStream dis = new DataInputStream(System.in );
              System.out.println(“Enter any value : ”);
              a= Integer.ParseInt(dis.readLine() );
            System.out.println(“The value user entered is” +a);
         }
    }

OUTPUT:

 Enter any value :

2 --  >> User entered

The value user entered is 2

HOW TO GET STRING  AS AN INPUT FROM THE USER..??

          Hmm.. getting Integer, Decimal etc from the user involves similar procedure but what if we want to get the String as an Input from the user..??

WHAT IS A STRING..??

         A string is nothing but Sequence of characters.If you like to more about string class and its methods please refer the Strings in JAVA

     To declare a String datatype,

String a;

is the syntax.

The code now changes to,

     Class Happy
       {
          public static void main(String args) throws IOException
            {
            String a;
            DataInputStream dis = new DataInputStream(System.in );
            System.out.println(“Enter any string : ”);
             a=  dis.readLine() ;
            System.out.println(“The value user entered is” +a);
          }
      }

EXPLANATION:

        Initially we are declaring a String data type and DataInputStream remains same because it’s the way we are using to get the input from the user.

       But look the code    A=  dis.readLine() ;

       We are not using Integer.ParseInt here as we are not converting the Integer data type to String because we are passing only the String data type. So, we are using only dis.readLine( )

         This code gets the String input from the user and prints it in console.

OUTPUT:
  
    Enter any string :
    Hai I am anu
    The value user entered is Hai I am anu.

ANOTHER WAY OF GETTING INPUT FROM THE USER..

      Another way of getting the input from the user is using “SCANNER”
       The Syntax is as follows,

        Scanner scan = new Scanner(System.in);
        String s= Scan.readLine();

     The above syntax is to get the input in a String format. If we want to get in an Integer format then use,

       String s =Scan. nextInt( );

If we want to  get the double data type input from the user then we can use,

       String s1 = Scan.nextDouble( );

EXAMPLE:

   Class Happy
     {
        public static void main(String args) throws IOException
          {
         String a;
         int b;
         double c;
         System.out.println(“Enter 3 vales – string , integer, double : ”);
         Scanner scan = new Scanner(System.in);
         a= Scan.readLine(); // TO GET THE STRING INPUT
         b= Scan.nextInt( );
         c= Scan.nextDouble( );
         System.out.println(“The string user entered is” +a);

         System.out.println(“The integer user entered is” +b);
        System.out.println(“The double user entered is” +c);

         }

   }

OUTPUT:

   Enter 3 vales – string , integer, double :
   Boo ------------------ input
   5 --------------------- input
   5.2000 ---------------- input
   The string user entered is Boo
   The integer user entered is 5
   The double user entered is 5.2000

EXPLANATION:

     So..this is another way of getting input from the user. This method is widely used since it is user friendly.

CONCLUSION:

      So.. that’s it for this post. Please leave your valuable comments below . It will help me improve . Request for the post you wish is welcomed. If you want some tutorials in Asp.Net and Android then email me. Stay tuned for more posts. Have a blissful day :)