Author: admin

  • Java – Garbage Collection

    Garbage collection in java is a way in which the unreachable objects are destroyed to free up space in memory.

    JVM creates a heap area which is called runtime data area, where all the objects are stored. And the space in that area is limited so it is needed to manage this area efficiently by removing the objects that are no longer required or are unused. And therefore, this process of removing the unused objects present in the heap area is known as Garbage collection.

    It runs automatically in the background and is a part of a memory management system in Java.
    Unlike Java, c/c++ doesn’t support Garbage collection.

    Benefits/Advantages of using garbage Collection:

    • Removal of unreferenced objects present in a heap memory makes the memory more efficient for use.
    • The automatic removal of objects makes it faster and users do not need to make an extra effort.

    finalize() method:

    Before destroying an object, the finalize() method is called by Garbage Collector for performing the cleanup process. And once it’s done, Garbage Collector destroys that object.

    The finalize() method is present in an Object Class as:

     protected void finalize(){} 

    gc() method:

    This method is used when needed to invoke the garbage Collector for the cleanup process.

     public static void gc() {} 

    Example of Garbage Collection in Java:

    public class GarbageCollectionTest
     {  
      public void finalize()
      {
         System.out.println("Garbage Collected");
      } 
     
      public static void main(String args[])
      {  
       GarbageCollectionTest g1=new GarbageCollectionTest();  
       GarbageCollectionTest g2=new GarbageCollectionTest();  
      
       g1=null;  
       g2=null;  
      
       System.gc();  
      }  
     }

    Output of Garbage Collection:

     Garbage Collected
     Garbage Collected

  • Java – Packages and its types with example

    Packages in Java are a way to pack(group) a number of related types such as classes, interfaces, enumerations, and annotations together into a single unit. Think of it as a container for the classes.

    Packages are used to avoid name conflicts, provide a good structure to the projects with maintainable code that consists of many classes.

    Reason to use Packages(advantages):

    • It provides the reusability of the same code again and again in the program by creating a class inside a package for that particular task.
    • The name of the two classes can be defined by the same name in two different packages and we can avoid name conflicts using packages.
    • We can hide the classes in packages if the user doesn’t want it to be accessed by other packages.
    • Hundreds of classes used in packages are organized in a better way so that when needed it can be easily accessed by the programmer.

    Creating Package in Java:

    We can create a package in java by declaring the keyword ‘package’ followed by the ‘packageName‘.
    Syntax:

     package mypack;

    Syntax to compile the program.

     javac -d Destination/Directory_folder file_name.java

    Note:
    The -d in here specifies the destination/directory to put the generated class file.
    Other directory names can be used such as d:/xyz (in case of windows) etc.
    And to keep the package within the same directory we need to use. (dot).

    Syntax to run the Java Program:

    java package_Name.Class_Name

    Let us see it in an example:

    //save as CreatingPack.java  
     package pack1;  
     public class CreatingPack
     {  
      public static void main(String args[])
      {  
        System.out.println("Hello! I am Package");  
      }  
     }

    To compile:

     javac -d . CreatingPack.java 

    To run:

     java pack1.CreatingPack

    Output:

     Hello! I am Package

    import Keywords:

    If the user needs to access or use the class of some other package in his/her current package, then it can be done with the help of the import keyword. import keyword imports the packages with reference to all classes or a particular class of that imported package.

    This keyword is used to import both Built-in Packages and User-defined Packages. You can see the use of import below in examples.

    Accessing Classes from Packages:

    It can be done in the following ways,

    1. Using fully qualified name:

    When we use a fully qualified name then we do not need to use import but need to use a fully qualified name every time we want to access the class or interfaces of that other package.

    Example of Using fully qualified name in Java:

    //save by Class1.java  
     package pack1;  
     public class Class1
     {  
      public void display()
      {
        System.out.println("Display Accessed");
      }  
     }
    
     //save by class2.java  
     package mypack2;  
     class class2
     {  
      public static void main(String args[])
      {  
        pack1.Class1 obj = new pack1.Class1(); //using fully qualified name  
        obj.display();  
      }  
     }

    Output:

    Display Accessed

    2. import only selected class from a package:

    This is the way in which the user can only access those classes that are required from the package. This is done by import packageName.className

    Example of importing only selected class from a package in Java:

    //save by Class1.java  
     package pack1;  
     public class Class1 
     {  
      public void display() 
      {
        System.out.println("Display Accessed");
      }  
     }  
    
     //save by Class2.java  
     package pack2;  
     import pack1.Class1;  //class1 is accesed from pack1 package
     class Class2 
     {  
      public static void main(String args[]) 
      {  
        Class1 obj = new Class1();  
        obj.display();  
      }  
     } 

    Output:

    Display Accessed

    3. import all the classes from a selected package:

    ‘*’ is used instead of className when the package is imported. But the classes and packages that are present inside the sub-packages cannot be accessed. This can be done by import packageName.*;

    Example of import all the classes from a selected package in Java:

    //save by Class1.java  
     package pack1;  
     public class Class1
     {  
      public void display() 
      {
       System.out.println("Display Accessed");
      }  
     }  
    
     //save by Class2.java  
     package pack2;  
     import pack1.*; //importing all classes from pack1 package   
     class Class2 
     {  
      public static void main(String args[]) 
      {  
       Class1 obj = new Class1();  
       obj.display();  
      }  
     }

    Output:

     Display Accessed

    Sub-Packages:

    The package within another package is called sub-package.

    Example of Sub-packages in Java:

    If we create a package called ‘Add’ inside a package named ‘AddNumber’ then the Add is called sub-package and it will be declared as package AddNumber.Add

     //saved  Addition.java
     public class Addition 
     {
      int sum(int x, int y)
      {
        return x*y;
      }
     }

    And to use this class present in a sub-package we can either import the package or use fully qualified name.

    Importing a package:

     import AddNumber.Add.Addition;

    using a fully qualified name:

     AddNumber.Add.Addition obj = new AddNumber.Add.Addition();

    Categories of packages:

    • Built-in Packages (Java API)
    • User-defined Packages (self-created)

    1. Built-in Packages (Java API) :

    These are already defined packages in Java. Java APIs are the already defined classes that are provided for free use.

    The mostly use built-in packages are:

    • java.lang
      Contains classes for primitive data types, strings, math operations, threads, and exception.
    • java.util
      contains utility classes such as vectors, hash tables, dates, etc.
    • java.io
      Stream classes for input/output operations.
    • java.awt
      Contain classes for implementing GUI such as buttons, menus, etc.
    • java.net
      Classes for networking operations.
    • java.applet
      Contain classes for creating and implementing applets.

    Example: If the user input is required, we import Scanner and following is the way to do it:

    import java.util.Scanner

    2. User-defined Packages (self-created):

    These packages are created/defined by the user themself. Users need to create a directory ‘egPackage‘ and name should match with the name of the package. Then the user can create a class (EgClass) inside that directory by declaring the first name as the package name.

     // Name of the package must must match with the directory where the file is saved
     package egPackage;
    
     public class EgClass
     {
      public void detail(String s)
      {        
       System.out.println(s);        
      }
     }

    And now the user can use this package in another program by importing it.

    //importing the class 'EgClass' from egPackage
     import egPackage.EgClass;
    
     public class DisplayClass 
     {
      public static void main(String args[]) 
      {       
       String disp = "Diplaying the details";
    
       EgClass obj = new EgClass();
    
       obj.detail(disp);
      }
     }

    Output:

     Diplaying the details
  • Java – Method Overriding with Example, Super Keyword

    In any object-oriented programming language, Method Overriding is a feature that allows the user to declare a method with the same name in a sub-class that is already present in a parent-class.

    That is when a sub-class inherits from its super-class and both have the same-named method than by overriding features, different tasks can be applied to both of the methods.

    Method overriding is used for runtime Polymorphism.

    Example of method overriding in Java:

     class Dog 
     {
        public void display() 
        {
            System.out.println("I am A Dog");
        }
     }
    
     class breed extends Dog 
     {
        public void display() 
        {
            System.out.println("Breed: German Shepard");
        }
     }
    
     public class BreedTest 
     {
    
        public static void main(String args[]) 
        {
            Dog d = new Dog();   // Animal reference and object
            Dog b = new breed();   // Animal reference but Dog object
    
            d.display();   // runs the method in Animal class
            b.display();   // runs the method in Dog class
        }
     }

    Output method overriding:

    Cat meows
    I am A Dog
    Breed: German Shepard

    Explanation:
    In the above example, we can see that ‘b‘ is a type of dog but still executes the display method in the breed class. In the runtime, JVM first looks at the object type and runs the method that belongs to that particular object.

    Since the class Dog has the method display, the compiler will have no problem in compiling, and during runtime, the method specific for that particular object will run.

    But look at the below example:

     class Dog 
     {
        public void display() 
        {
            System.out.println("I am A Dog");
        }
     }
    
     class breed extends Dog 
     {
        public void display() 
        {
            System.out.println("Breed: German Shepard");
        }
        public void dogSleep()
        {
        System.out.println("Dog is Sleeping");
        }
     }
    
     public class BreedTest 
     {
    
        public static void main(String args[]) 
        {
            Dog d = new Dog();   // Animal reference and object
            Dog b = new breed();   // Animal reference but Dog object
    
            d.display();   // runs the method in Animal class
            b.display();   // runs the method in Dog class
            b.dogSleep();
        }
     }

    Output:

     BreedTest.java:31: error: cannot find symbol
           b.dogSleep();
            ^

    Here it shows an error for the method doSleep() because the object created is of type Dog that does not have the dogSleep() method and is not Overriden in the breed class.


    Rules for Overriding a Method:

    • The Overriden and Overriding methods must have the same name and the same argument list.
    • Method Overriding requires Inheritance of a class otherwise the method cannot be overridden.
    • Restriction to use Access-modifier, that is if a, access-modifier of the method is declared public in a parent class then it cannot be an overriding method of a sub-class or child-class cannot have protected, private and default access-modifier.
    • private, static and final methods cannot be overridden as they are local to the class. But the static method can be re-declared.
    • A child class within the same package as the instance’s parent class can override any parent class method that is not declared private or final.
    • Constructors cannot be overridden.
    • Overriding method (that is the method present in the sub-class) can throw unchecked exceptions, whether the Overriden method (that is the method present in the parent-class) throws an exception or not.

    Use of Super keyword in Method Overriding:

    The super keyword in Java is used in the sub-class for calling the inherited parent class method/constructor. When we execute super.myMethodName in sub-class inside the method, it invokes the method of parent-class having method name ‘myMethodName’.

    Example of Super keyword in Method Overriding:

    class Dog 
     {
        public void display() 
        {
            System.out.println("I am A Dog");
        }
     }
    
     class Breed extends Dog 
     {
        public void display() 
        {
            super.display();
            System.out.println("Breed: German Shepard");
        }
        
     }
    
     public class BreedTest 
     {
    
        public static void main(String args[]) 
        {
            
            Breed b = new Breed();
    
            b.display(); 
            
            
        }
     }

    Output:

    I am A Dog
    Breed: German Shepard

    In this example, we create the Object for Breed class. And ‘super.display()’ calls the ‘display()‘ method from the Dog class that is the parent class. and hence we get ‘I am a Dog‘ result too.
    But if we eliminate ‘super.display()‘ then we only get the result as ‘Breed: German Shepard‘.


  • Java – Method Overloading with Example

    Method Overloading is one of the features in a class having more than one method with the same name. It is the same as Constructor Overloading in java. The methods are differed by their input parameter that is the data type, the number of parameters, and the order of the parameter list.

    Note that: Method overloading is not possible by changing the return type of methods.

    Now let us see the different ways of overloading methods.

    There are two different ways in which the method can be overloaded:

    1. Method overloading, by changing the data type of Arguments.
    2. Method overloading, by changing the number of the argument.

    1. Method overloading by changing the data type of Arguments.

    In this method, the user needs to change the data-type of passing argument for two different methods of the same name and the parameter list must match with that data type accordingly.

    The following program shows the example of using Method overloading by changing the data type of Arguments in Java:

    class MethOverloadingTest
     {
        void add (int x, int y)
        {
        System.out.println("sum is "+(x+y)) ;
        }
        void add (double x, double y)
        {
        System.out.println("sum is "+(x+y));
        }
     }
    
     public class Main
     {  
        public static void main (String[] args)
        {
        MethOverloadingTest  sum = new MethOverloadingTest();
        sum.add (5,5);      // method with int parameter is called.
        sum.add (5.5, 5.5); //method with float parameter is called.
        }
     }

    The output of Method overloading:

    sum is 10
    sum is 11.0


    2. Method overloading by changing the number of the argument.

    Another way is by changing the number of arguments that is the number of parameters passed when called. We can also keep the argument empty and it will recognize the method with an empty parameter list.

    Following is the example method overloading by changing the number of arguments in Java:

    class MethOverloadingTest2
     {
        void Info()
        {
         System.out.println("Argument List is empty") ;
        }
        void Info (String c, int id)
        {
         System.out.println("\nName:"+c+" Id:"+id);
        }
        void Info (String c, int id, int age)
        {
         System.out.println("\nName:"+c+" Id:"+id+" Age:"+age);
        }
     }
    
     public class Main
     {  
        public static void main (String[] args)
        {
          MethOverloadingTest2  sum = new MethOverloadingTest2();
          sum.Info(); //method with empty parameter is called.
          sum.Info ("Karan",1101);      // method with two parameter is called.
          sum.Info ("Prashant",1102,23); //method with three parameter is called.
        }
     }

    The output of Method overloading:

    Argument List is empty

    Name:Karan Id:1101

    Name:Prashant Id:1102 Age:23


  • Method in Java

    Java Method is a collection of statements that are put together to perform some specific task. To run the methods, it should be called and it returns the value to the caller. Users can pass data to the methods and those data are known as parameters. They are also known as a function.

    It allows the user to reuse the code as many times without rewriting the code and therefore act as a time saver.

    Syntax of method:

     modifier returnType methodName (Parameter List) 
     {
        // method body
     }
    
     //example
     public int calculate(int x, int y) 
     {
        // statements
     }

    Explanation:

    Modifier:

    It is optional and defines the access type of a method. In the above example, the ‘public’ is the modifier of the method calculates.

    Return Type:

    The return type is for returning the value by defining the data-type of the method or void is used if the method does not return a value. In the above example, ‘int’ is the data type for the return type.

    MethodName:

    It is the name given to the method to identify the specific method. ‘calculate is the method name in the above example.

    Parameter List:

    These are the input parameters with their specific data types. The passed parameter data type must match with the parameter list of a method and also the order in which it is passed and must be separated by commas(,). If there are no parameters, the user needs to use an empty parentheses ‘()’. ‘int x, int y’ is the parameter list in the above example.

    Method body:

    The method body is enclosed within the curly braces'{}’. It defines the task of a method within the curly braces.


    Call A Method:

    To use the method and its functionality in a program it must be called. To call a method, the user needs to write the method name followed by two parentheses ‘()’ and a semicolon ‘;’. When a program calls a method, the control of a program remains with the method and then again return the control to the caller in two conditions:

    1. If completes all the statements within the curly braces ‘{}’.
    2. If the return statement is executed.

    Basic example to call a method more than once with empty parameter List in Java:

    public class MethodTest 
     {
     //creating a void method
        static void myMethod() 
        {
        System.out.println("I am called");
        }
    
        public static void main(String[] args) 
        {
        myMethod();//method called
        myMethod();//method called
        }
     }

    Output:

     I am called
     I am called 

    Void Keyword:

    This Keyword allows us to create methods that do not return any values.

    Basic example to find the max number with method parameter and with return type in Java:

    public class MethodTest 
     {
       //creating a method //static method mean accessing the static variable without object
        public static int maxMethod(int a, int b) 
        {
         int max;
         if (a < b)
            max = b;
         else
            max = a;
    
         return max; //returning the result and also return the control
        }
        
        public static void main(String[] args) 
        {
         int x = 20;
         int y = 25;
         int z = maxMethod(x, y);
         System.out.println("The Maximum Value : " + z);
        }
     }

    Output:

     The Maximum Value : 25

    Method Types

    There are two types of method:

    • Standard Library Methods
    • User-defined Methods: In the above part we lean about the User-defined methods.

    Standard Library Methods:

    These methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.

    Some example of Standard Library Methods:

    • print() -use to print the String.  And it comes under java.io.PrintSteam
    • sqrt() -use to find the square root of the number and it is a method of Math class

  • Inner Class in Java

    Java Inner class is also known as the nested class is a class within the class, method, or block declared inside class or interface. The use of the inner class is to group the classes or interfaces logically in one place so that it becomes easy to read and maintain.

    Java Inner class is of two types:

    A. Non-static nested classes

    • Member inner class
    • Anonymous inner class
    • Local inner class

    B. Static nested classes


    A. Non-static nested classes in Java: (Inner class)

    It is one of the types of java Inner class. As we have learned from the Access modifiers that we cannot declare a class with ‘private’ modifiers. But the inner class, that is the member of the other class is declared then we can have the inner classes as ‘private’.

    An inner class is of the following types:

    • Member inner class
    • Anonymous inner class
    • Local inner class

    1. Member inner class:

    It is a Non-static nested class (inner class) that is declared inside a class and outside all the methods or blocks. If we declare it as private then that inner class cannot be invoked from an object outside the outer class of that inner class.

    Syntax for member inner class in Java:

    class OuterClass
     {  
      //code  
      class InnerClass
      {  
       //code  
      } 
     
      //methods
    
     } 

    Let us use it in a program:

    In the following example, we declare the private inner class within the outer class, which also contains a method ‘displayingInner()’ that instantiates an inner class and invokes the method that is present inside the inner class.

    And the Main class instantiates the Outerclass class and invokes the method ‘displayingInner()’, that is the nesting done here.

    Note: That the InneerClass cannot be accessed outside the outer class because of its private modifier but it can be accessed by the method inside the OuterClass.

    To demonstrate the example if Member inner Class in Java:

    class OuterClass 
     {
        
       // inner class declaring as private
       private class InnerClass 
       {
         public void displayInner() 
         {
           System.out.println("Inner class Acceseed");
         }
       }
        
       // method for accessing the inner class
       void displayingInner() 
       {
         InnerClass in = new InnerClass();
         in.displayInner();
       }
     }
        
     public class Main 
     {
    
       public static void main(String args[]) 
       {
        // Instantiating the outer class 
        OuterClass out = new OuterClass();
          
        // Accessing the displayingInner method.
        out.displayingInner();
        }
     }

    Output:

    Inner class Acceseed

    2. Anonymous inner class:

    Anonymous inner class is a class that does not contain the class name. They are used in a class or interface whenever the user needs to override the methods. The declaration and instantiation of the Anonymous inner class are done at the same time.

    There are two ways in which this class can be created. They are:

    • First Subclass or maybe abstract
    • Second interface

    Let us see it individually:

    Example of Anonymous inner class Using class in Java:

    abstract class Dog
     {  
        abstract void bark();  
     }  
     public class TestAnonymousInner
     {  
      public static void main(String args[])
      {  
        //An anonymous class
        Dog d = new Dog()
        {  
         void bark()
         {
          System.out.println("The dog is barking");
         }  
        };
        
        d.bark();  
      }  
     }

    Output:

    The dog is barking

    Example of Anonymous inner class using interface in Java:

    interface Dog
     { 
      void display(); 
     }
    
     public class Flavor2Demo 
     { 
       public static void main(String[] args) 
       {
        // An anonymous class 
        Dog d = new Dog() 
        { 
         public void display() 
         { 
            System.out.println("I am a good Dog"); 
         } 
        }; 
        
         d.display(); 
       } 
    } 

    Output:

    I am a good Dog

    3. Local inner class:

    The class that is declared within the method of an outer class is called the Local inner class or method-local inner class. As the name suggests local, that is its restriction is within that method only, just like a local variable.

    Example to demonstrate the local inner class in Java:

    public class OuterClass
    {  
      void MethodOuter()
      {  
       System.out.println("Outer Class Method");
            
       class LocalClass   //Local Inner class
       {  
        void MethodInner()
        {
          System.out.println("Inner Class Method");
        }  
       }  
        LocalClass c = new LocalClass();  
        c.MethodInner();  
      }
        
        public static void main(String args[])
        {  
         OuterClass o = new OuterClass();  
         o.MethodOuter();  
      }  
    }

    Output:

    Outer Class Method
    Inner Class Method


    B. Static nested classes:

    If a class within another class that is the nested class has the static modifier declared in it, then it is called a static nested class. As this class is applied static, it will not be able to access the instance variables and methods of the outer class, it can only access the static member of the outer class.

    Example: Accessing static method of a static class in Java,

    public class OuterClass
     {  
      void MethodOuter()
      {  
       System.out.println("Outer Class Method");
        
       class LocalClass   //Local Inner class
       {  
        void MethodInner()
        {
          System.out.println("Inner Class Method");
        }  
       }  
       LocalClass c = new LocalClass();  
       c.MethodInner();  
      }
    
      public static void main(String args[])
      {  
        OuterClass o = new OuterClass();  
        o.MethodOuter();  
      }  
     }

    Output Static nested classes:

    I am Inner Class


  • Java – What are Access Modifiers?

    The access modifiers in Java specifies the accessibility or visibility or scope of a field, method, constructor, or class. Java defines four access modifiers:

    Following shows their accessibility,

    1. default (Same class, Same package)
    2. private (Same class)
    3. protected ( Same class, Same package, Subclasses)
    4. public ( Same class, Same package, Subclasses, Everyone)
    Java Modifiers

    1. default:

    Default access modifiers mean, no modifiers are specified to the class, method, or data members. These parts where no access modifiers are specified that are having a default modifier are only accessible within the same package.

    let us see an example:
    In this example we created two packages ‘name’ and ‘mainPack’. ‘name’ package contains the default access modifiers class and method. Now if we import this package in the mainPack then we will get a compile-time error because the class ‘Names’ is only accessible within that package.

    //save by Names.java  
     package name;  
     class Names
     {  
        void myName()
        {
            System.out.println("I am John");
        }  
     }
     
     
     //save by Main.java  
     package mainPack;  
     import pack.*;  
     class Main
     {  
        public static void main(String args[])
        {  
        Names n = new Names(); 
        n.myName();//Compilation Error  
        }  
     }

    2. private:

    It is specified using the private keyword. Variables, Methods, and constructors that are declared private modifiers are only accessed within the declared class itself. Any other package cannot access them. Classes and Interfaces cannot be declared as private but can only be applied to inner classes.

    In this example, a class named ‘Name’ contains a private method called ‘display()’ which cannot be accessed in another class Main, showing the error result.

     class Name
     { 
        private void display() 
        { 
        System.out.println("I am John"); 
        } 
     } 
        
     public class Main 
     { 
        public static void main(String args[]) 
        { 
        Name n = new Name(); 
        //accesing the private method of another class
        n.display(); 
        } 
     }

    Output:

     java:15: error: display() has private access in Name
               n.display(); 

    3. protected:

    Variables, methods, and constructors, which are declared protected using the keyword ‘protected‘.
    Protected data methods and members are only accessible by the classes of the same package and the subclasses present in any package. Classes and Interfaces cannot be declared protected.

    Let us see it in an example:
    The two packages Pack1 and pack2 are declared where pack1 contains the protected method ‘display()’ and is accessed in pack2 by importing pack1 in it. In this example, the protected method ‘display()’ declared in a class ‘Name’ is accessed by class Main.

    //save by Name.java 
     package pack1; 
      
     public class Name 
     { 
       protected void display() 
       { 
         System.out.println("I am John"); 
       } 
     } 
    
    
     //save by Main.java  
     package pack2; 
     import pack1.*; //importing from pack1 
      
     //inheriting Name class
     class Main extends Name
     { 
       public static void main(String args[]) 
       {   
        Name obj = new Name();   
        obj.display();   
       }   
     }

    Output:

    I am John

    Note:
    Methods and fields cannot be declared protected in an Interface.


    4. Public:

    Declaring fields and methods or classes public means making it accessible everywhere in a program or in an application. A public entity can be accessed from class in a program. However, if the needs to access the public class from the different packages then in order to access it that package must be imported first.

    Let us see it in an example:
    Two classes Mult and Main are created for different packages, named pack1 and pack2. Mult class is declared public and its method ‘multTwoNumber’ is also declared public and so to access it in a ‘Main’ class its package must be imported that is pack1 is imported in Main.java.

    //saved by Mult.java
     package pack1;
    
     public class Mult
     {
    
        public int multTwoNumber(int x, int y)
        {
        return x*y;
        }
     }
    
     //saved by Main.java
     package pack2;
     import pack1.*;
     class Main
     {
        public static void main(String args[])
        {
            Mult mul = new Mult();
            System.out.println(mul.multTwoNumber(5, 10));
        }
     }

    Output:

    50


  • Java – Interface with Syntax and Example

    An Interface in Java is the same as a class, like any other class, an interface can have methods and Variables. But unlike a class, the method in it is an abstract method (only method signature, contain no body), and also by default, the declared variables in an interface are public, static & final.

    Uses of Interfaces:

    • It is used to achieve abstraction.
    • As we have learned that Java does not support multiple inheritance but through the interface, we can achieve multiple inheritance.
    • It is also used to achieve loose coupling.

    Note: Abstraction cannot be used to create objects. Hence it cannot contain a constructor.

    Declaring an Interface in Java:

    The keyword ‘interface‘ is used to declare an interface. Syntax of Interface in Java:

    interface interface_name 
     {
        
      // declare constant fields, abstract methods
    
     }

    Example of interface:

    interface Dog
     {
        public void bark(); // interface method 
        public void run(); // interface method
     }

    Implementation of Interface in Java:

    To implement an interface in a class, we use the keyword ‘implements’ The following example shows the use of implements. In the example below, the class Puppy implements the interface Dog.

    interface Dog 
     {
        public void bark(); // interface method 
        public void eat(); // interface method 
     }
    
     // implementing Dog
     class Puppy implements Dog 
     {
        public void bark() 
        {
        // Body of a bark() method
        System.out.println("Dog Barks");
        }
        public void eat() 
        {
        // Body of a eat() method
        System.out.println("Dog eat Bones");
        }
     }
    
     public class MyMainClass 
     {
        public static void main(String[] args) 
        {
        Puppy pup = new Puppy();  //Puppy object
        pup.bark();
        pup.eat();
        }
     }

    Output of Interfaces in Java:

    Dog Barks
    Dog eat Bones


    Multiple Interfaces and inheritance in Java:

    We know class in java allows only a single extends but with the use of interfaces, we can implement more than one parent interface.

    Java Interface

    In the diagram above,

    • The class extends a class
    • The interface extends an interface
    • class implements interface

    Example of Multiple Interface in Java:

    interface Interface1 
     {
        public void firstMethod(); // interface method
     }
    
     interface Interface2 
     {
        public void secondMethod(); // interface method
     }
    
     // InClass "implements" the above two interface
     class Inclass implements Interface1, Interface2 
     {
        public void firstMethod() 
        {
        System.out.println("Displaying first method");
        }
        public void secondMethod() 
        {
        System.out.println("Displaying second method");
        }
     }
    
     public class MyMainClass 
     {
        public static void main(String[] args) 
        {
        Inclass Obj = new Inclass();
        Obj.firstMethod();
        Obj.secondMethod();
        }
     }

    Output:

    Displaying first method
    Displaying second method


  • Java – Constructor with Example

    A constructor is a block of codes just like a method in Java. It is a special type of method that is called when an instance of the class (that is object) is created and is used for the initialization of the data members of a newly created object.

    There are some rules for Java constructor:

    • The constructor name must be the same as its class name.
    • It should not have any return type not even void.

    Types of Constructors in java:

    • Default constructor(no-argument constructor)
    • Parameterized constructor.

    Default constructor(no-argument constructor):

    This constructor does not have any parameter and is hence called a no-argument constructor.

    Syntax of default constructor in Java:

     public class className
     {
        className() //default constructor
        {
          ......
        } 
     }

    Basic Example: Program to create and call a default constructor in Java:

    public class Car
    {
      //creating a default constructor  
      Car()
      {
        System.out.println("Car is created");
      }
    
      public static void main(String args[])
      {
        //calling a default constructor  
        Car c = new Car();
      }
    }

    Output of Default constructor:

    Car is created

    Note: Default Constructor is used if the user does not define a constructor then the java compiler creates a default constructor and initializes the member variables to its default values. That is numeric data types are set to 0, char data types are set to the null character.


    Basic Example for displaying the default values in Java:

     public class Employee
     {
       int id;
       String name;
       int age;
    
       //Method for Displaying default values  
       void display()
       {
         System.out.println(id + " " + name + " " + age);
       }
    
       public static void main(String args[])
       {
         //creating objects  
         Employee e1 = new Employee();
         Employee e2 = new Employee();
    
         e1.display();
         e2.display();
       }
     }

    Output:

    0 null 0
    0 null 0


    Java Parameterized Constructor:

    A Parameterized Constructor is a constructor having a specific number of parameters. The parameter is added to a constructor as they are added to the methods that are inside the parentheses of the constructor.

    The data type must match with values that are passed and in that particular order and number.

    Example of Parameterized Constructor in Java:

    public class Employee
    {
      int id;
      String name;
      int age;
    
      //parameterized constructor  
      Employee(int i, String n, int a)
      {
        id = i;
        name = n;
        age = a;
      }
    
      //display the values  
      void display()
      {
        System.out.println(id + " " + name + " " + age);
      }
    
      public static void main(String args[])
      {
        //creating objects and passing values  
        Employee e1 = new Employee(101, "John", 30);
        Employee e2 = new Employee(105, "Ron", 32);
    
        //calling display method 
        e1.display();
        e2.display();
      }
    }

    Output:

    101 John 30
    105 Ron 32


    Constructor Overloading in Java:

    Constructor Overloading is like a method of overloading in Java. This is a technique in Java where a single class has more than one Constructor and each of them has a different parameter. The number of parameters and their data types differs for each constructor by the compiler.

    Example of Constructor Overloading in Java :

    public class Employee
    {
      int id;
      String name;
      int age;
    
      //parameterized constructors 
      Employee(int i, String n, int a) //three parameters
      {
        id = i;
        name = n;
        age = a;
      }
    
      Employee(int i, String n)  //two parameters
      {
        id = i;
        name = n;
      }
    
      //displaying three parameterized constructor  
      void display1()
      {
        System.out.println("Displaying three parameterized constructor ");
        System.out.println(id + " " + name + " " + age);
      }
    
      //displaying two parameterized constructor
      void display2()
      {
        System.out.println("\nDisplaying three parameterized constructor ");
        System.out.println(id + " " + name);
      }
    
      public static void main(String args[])
      {
        //creating objects and passing values  
        Employee e1 = new Employee(101, "Prashant", 30);
        Employee e2 = new Employee(105, "Karan");
    
        //calling display method for each constructor 
        e1.display1();
        e2.display2();
      }
    }

    Output:

    Displaying three parameterized constructor
    101 Prashant 30

    Displaying three parameterized constructor
    105 Karan


  • Java – Class and Objects with Example

    Java is an Object-Oriented Language. And classes and objects are the fundamental components of OOP’s.

    Objects are real-life entity and classes are the blueprint for creating an object. For example: consider a class for a car, it has color, some weight, size, etc, these are its attributes and drive, gear, brake, etc are its behaviour.

    CLASS

    A class is a user-defined blueprint or prototype for creating Objects. It is a logical entity. We can say that classes are categories, and objects are items within each of those categories.

    A class in Java contain:

    • Methods.
    • Fields.
    • Constructors.
    • Interfaces.

    For the declaration of a class following components are included:

    1. Modifiers:
    A class can be public or default access.

    2. Class name:
    A class should have a name with an initial letter Capitalized.

    3. SuperClass(if any)/ Interfaces:
    If required to include SuperClass then proceed by the keyword ‘extends’. Using the keyword implements, a class can have more than one interface.

    4. Body:
    A class boundary is within the curly braces'{}’.

    Syntax for class:

    class ClassName
    {
      // field;  
      //method;
    }

    Syntax example:

    public class Dog
     {
      //variables
      int age;
      String color;
    
       //Methods
      void eat()
      {
            
      }
      void bark()
      {
        
      }
    }

    OBJECTS:

    It can be defined as real-world entities that have state and behavior. An object is a runtime entity. Eg. bike, Lamp, pen, table, etc. An Object is an instance of a class. It is a physical as well as a logical entity.

    Objects has three characteristics:

    • State: It is represented by attributes of an object that is the data value.
    • Behaviour: It represents the functionality that is the behaviour of an object. Example withdraw, deposit, etc.
    • Identity: It is a unique ID given to each Object created so that JVM can identify all the objects uniquely.

    Example:
    Name of an Object: dog
    Identity: Name of the dog.
    State: age, color, breed, size, etc.
    Behaviour: eat, sleep, bark, run, etc.

    Creating an Object:

    As mentioned above that class is a blueprint for objects. So, Object is created from a class. And ‘new’ Keyword is used to create an Object.Three steps to create Object:

    • Declaration: Declaration of a variable with the variable name with an object type.
    • Instantiation: When an object of a class is created, it is said to be instantiated. And the ‘new‘ keyword is used to create an object.
    • Initialization: The ‘new’ operator allocates memory for a new object that is being instantiated. Also invokes the class constructor.

    Syntax of Object:

    ClassName ReferenceVariableName = new ClassName(); 

    Following Example shows the creation of an Object:

     public class Dog 
     {
        //constructor having  one parameter 'name'
        public Dog(String dogName) 
        {
          System.out.println("My Dog Name is :" + dogName );
        }
    
        public static void main(String []args) {
          // Creating an Object
          Dog myDog = new Dog( "Bruno" );
        }
     }

    Output:

     My Dog Name is :Bruno

    Creating Multiple Objects:

    Multiple Objects can be created for the same class.

    The following example shows that Objects are created for One class, invoking different variables.

    class MyClass 
     {
      int x = 10;
      int y = 20;
         
     }
      public class Main
      {
    
        public static void main(String[] args) 
        {
         MyClass Obj1 = new MyClass();
         MyClass Obj2 = new MyClass();
         System.out.println("Value of x:" +Obj1.x);
         System.out.println("Value of y:" +Obj2.y);
        }
     }

    Output:

     Value of x:10
     Value of y:20

    Example of class and objects in Java:

    public class Dog 
     {
       // Instance Variables 
       String name;
       int age; 
       String color; 
    
      // Constructor Declaration of Class 
     public Dog(String name,int age, String color) 
     { 
       this.name = name;
       this.age = age;
       this.color = color;
     } 
     public void display()
     {
            
        System.out.println("Hi my name is "+ name); 
        System.out.println("My age is "+ age);
        System.out.println("My body color is "+ color);
     }
    
    
     public static void main(String[] args) 
     { 
        Dog myDog = new Dog("Bruno",1,"white"); 
        myDog.display();
     } 
     }

    Output:

     Hi my name is Bruno
     My age is 1
     My body color is white