Category: Java Tutorial

  • 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

  • Java – Polymorphism

    Polymorphism means having many forms. The word “poly” means many and “morphs” means forms. In java, it is a concept that allows the user to perform a single action in different ways.

    Take a real-life example: Consider a man and at the same time he can be a father, a husband, an employee that is he is having a different character and posses different behavior in different situations.
    Similarly, a class in a program has a method and the subclass have the same method but with a different task to perform related to the first method. This is called polymorphism.

    In Java polymorphism is mainly divided into two types:

    • Compile-time Polymorphism or Static Polymorphism.
    • Runtime Polymorphism or Dynamic Polymorphism.

    1. Compile-time Polymorphism:

    It is also known as static polymorphism. In this type of program, the flow of control is decided at compile time itself and if any error is found, they are resolved at compile time. This can be achieved by method overloading.

    Method Overloading:

    Method Overloading allows the user to have more than one method that has the same name, they are differed by the number of the parameter lists, sequence, and data types of parameters.

    Example: With a number of arguments

    class ExampleTest
    {
      int add(int x, int y)
      {
        return x + y;
      }
      int add(int x, int y, int z)
      {
        return x + y + z;
      }
    }
    public class Main
    {
      public static void main(String args[])
      {
        ExampleTest obj = new ExampleTest();
        System.out.println(obj.add(50, 30));
        System.out.println(obj.add(20, 10, 20));
      }
    }

    Output:

    80
    50


    2. Runtime Polymorphism:

    It is also known as Dynamic Method Dispatch. It is a process in which a call to an overridden method is resolved at runtime. This type of polymorphism is achieved by Method Overriding.

    Method Overriding: 

    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. And that base is said to be overridden.

    Example for Method Overriding:

    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:

    I am A Dog
    Breed: German Shepard


  • Abstraction in Java

    Data abstraction is the process of hiding the details but only displaying the relevant information to the users, which means hiding the implementation details and displaying only its functionalities. This is one of the main advantages of using abstraction.

    Abstraction is one of the four major concepts behind object-oriented programming (OOP).

    Real Life Example of Abstraction in Java

    Suppose a person is typing with the help of a keyboard on his/her computer. That person knows that pressing any alphabet on the keyboard, displays that alphabet on the screen of the monitor but he/she doesn’t know how the internal mechanism is working to display the alphabet.

    Therefore, hiding the internal mechanism and showing only its output is an abstraction in this example.

    In java, abstraction can be achieved in two ways.

    • Abstraction class.
    • Interfaces.

    Abstraction class and Abstract methods:

    • An abstract class is a class that is declared with an abstract keyword.
    • An abstract class may or may not have abstract methods.
    • An object of an abstract class cannot be created, to access this class, it must be inherited.

    Example:

    abstract class ClassName {}

    Abstract methods:

    • It is a method that can only be used with an abstract class.
    • It has no body.
    • An abstract method is also declared with an abstract keyword and ends with a semicolon(;) instead of curly braces({}).

    Example:

    public abstract void methodName();

    Let us see it in an example:

    // Abstract class
      abstract class AbstractTest 
      {
        public abstract void animals(); //abstract method
        
        public void dog() 
        {
          System.out.println("Dog barks");
        }
      }
      
      
      class Cat extends AbstractTest  //inheriting AbstractTest class
      {
        public void animals() 
        {
          // animals body 
          System.out.println("Cat meows");
        }
      }
      
      public class Main 
      {
        public static void main(String[] args) 
        {
          Cat c = new Cat(); // Create an object
          c.animals();
          c.dog();
        }
      } 

    Output:

    Cat meows
    Dog barks

    Also, go through an Interface in Java after abstraction


  • Java – Types of Inheritance

    Java supports three types of inheritance on the basis of class: single, multilevel, and hierarchical.

    Whereas multiple and hybrid inheritance is supported through interface only.

    Types of Inheritance in Java:

    • Single Inheritance
    • Multilevel Inheritance.
    • Hierarchical Inheritance.
    • Multiple Inheritance.
    • Hybrid Inheritance.

    1. Single Inheritance:

    It is a child and parent class relationship where a child class extends or inherits only from one class or superclass.
    In the below diagram, class B extends only one class which is A. Here class A is a parent class of B and B would be a child class of A.

    Single Inheritance

    Example of Single Inheritance in Java:

     class SuperClass
     {
       public void methodSuper()
       {
         System.out.println("Super class method");
       }
     }
    
     class SubClass extends SuperClass
     {
       public void methodBase()
       {
         System.out.println("Sub class method");
       }
     }
     public class Main
     {
       public static void main(String args[])
       {
         SubClass s = new SubClass();
         s.methodSuper();
         s.methodBase();
       }
     }

    Output of single Inheritance:

    Super class method
    Base class method


    2. Multilevel Inheritance:

    It is a child and parent class relationship where one can inherit from a derived class, thereby making this derived class the base class for the new class.
    In the below diagram, class C is a subclass or child class of class B and class B is a child class of class A.

    Multilevel Inheritance

    Example of Multilevel Inheritance in Java:

    class FirstClass
    {
      public void displayFirst()
      {
        System.out.println("I am First Class");
      }
    }
    
    class SecondClass extends FirstClass
    {
      public void displaySecond()
      {
        System.out.println("I am Second Class");
      }
    }
    
    class ThirdClass extends SecondClass
    {
      public void displayThird()
      {
        System.out.println("I am Third Class");
      }
    }
    
    public class Main
    {
      public static void main(String[] args)
      {
        ThirdClass three = new ThirdClass();
        three.displayFirst();
        three.displaySecond();
        three.displayThird();
      }
    }

    Output of Multilevel Inheritance:

    I am First Class
    I am Second Class
    I am Third Class


    3. Hierarchical Inheritance:

    In this type of inheritance, one superclass(base class) is inherited by many subclasses (derived class). That is inheriting the same class by many classes.
    In the below diagram class B and class, C inherits the same class A. Class A is parent class (or base class) of class B and class C.

    Hierarchical Inheritance

    Example of Hierarchical Inheritance in Java:

    class Animal
     {  
      void Dog()
      {
        System.out.println("I am dog");}  
     }  
        
     class Cat extends Animal
     {  
       void sleep()
       {
        System.out.println("I am Cat and I sleep");
       } 
     }
    
     class Horse extends Animal
     {  
       void run()
       {
        System.out.println("I am Horse and I run");
       }  
     }  
    
     public class Main
     {  
       public static void main(String args[])
       {  
        Horse h=new Horse();  
        h.Dog();  
        h.run();  
        
        Cat c=new Cat();  
        c.Dog();  
        c.sleep();
       }
            
     }

    Output of Hierarchical Inheritance:

    I am dog
    I am Horse and I run
    I am dog
    I am Cat and I sleep


    4. Multiple Inheritance:

    In this relationship, one class(derived class) can inherit from more than one superclass. Java doesn’t support multiple inheritance because the derived class will have to manage the dependency on two base classes.

    • In java, we can achieve multiple inheritance only through Interfaces.
    • It is rarely used because it creates an unwanted problem in the hierarchy.

    5. Hybrid Inheritance:

    It is the relationship form by the combination of multiple inheritance.
    In a simple way, Hybrid inheritance is a combination of Single and Multiple inheritance.
    It is also not supported in Java and can only be achieved through interface just like Multiple Inheritance.

    Multiple and Hybrid Inheritance diagram:

    Inheritance
    Supported through Interfaces

  • Java Encapsulation

    Encapsulation is one of the four fundamental OOP concepts. Encapsulation in Java is defined as the wrapping up of data(variable) under a single unit. The use of Encapsulation is to make sure that implementation detail or we can say sensitive data is hidden from the users. For this, Encapsulation is also known as data hiding.

    Implementing the encapsulation in the program, the variables or data declared in one of the classes is hidden from any other class.

    Encapsulation can be achieved in two ways:

    • Declare class variables/attributes as private, restricting other classes to access it.
    • Provide public setter and getter methods to modify and view the values of the variables.

    Benefits of Encapsulation:

    • Data- hiding in Java.
    • The class field can be made read-only or write-only.
    • It provides the class the total control over the data.

    Get and Set:

    As we know the private variable cannot be accessed by other classes, but we can access them by providing getter and setter methods.

    • The get method returns the variable value.
    • The set method sets the value.

    Note:
    Getter and Setter methods should start with get or set, followed by the variable name whose first letter should be in upper case. They both should be declared public. Since get returns value and set doesn’t get should be of data-type same as the variable it accesses and set must be declared void.

    Syntax Example:

      public class Student
      {
        private String name; // private
    
        // Getter
        public String getName() 
        {
        return name;
        }
    
        // Setter
        public void setName(String newName) 
        {
        this.name = newName;
        }
      }

    Let us go through a java example to understand better


    Encapsulation in Java using setter and getter

     class StudentInfo
     {
       private int id;
       private String stdName;
       private int stdAge;
    
       //Getter methods
       public int geStdiID()
       {
         return id;
       }
    
       public String getStdName()
       {
         return stdName;
       }
    
       public int getStdAge()
       {
         return stdAge;
       }
    
       // Setter methods
       public void geStdiID(int newId)
       {
         id = newId;
       }
    
       public void getStdName(String newName)
       {
         stdName = newName;
       }
    
       public void getStdAge(int newAge)
       {
         stdAge = newAge;
       }
     }
    
     public class EncapsTest
     {
       public static void main(String args[])
       {
         StudentInfo obj = new StudentInfo();
    
         obj.geStdiID(1101);
         obj.getStdName("Marshall");
         obj.getStdAge(20);
    
         System.out.println("Student Id: " + obj.geStdiID());
         System.out.println("Student Name: " + obj.getStdName());
         System.out.println("Student Age: " + obj.getStdAge());
       }
     }

    Output:

    Student Id: 1101
    Student Name: Marshall
    Student Age: 20