Tag: java OOP program

  • Example of this keyword in Java

    In this tutorial, we will write this keyword program in java. Before that, you should have knowledge on the following topic in Java.


    Example of this keyword in Java in constructor:

    class Student
     {
      String name;
      int marks;
    
      Student(String name, int marks)
      {
       this.name = name;   //use of this
       this.marks = marks; // use of this
      }
      void display()
      {
       System.out.println("Name: " + name + " marks:" + marks);
      }
     }
     public class main
     {
      public static void main (String[] args) 
      {
       Student st = new Student("Daniel", 90);
       st.display();
      }
     } 

    Output:

    Name: Daniel marks:90


    this: Invoke current class method:

    The method of the current class can be invoked by using this keyword. If this keyword is not used then the compiler automatically adds this keyword while invoking the method.

    source code:

     class Method
     {
      void m1()
      {
       System.out.println("This is method m1");
      }
      void m2()
      {
       System.out.println("This is method m2");
       this.m1();
      }
     }
     class Main
     {
      public static void main (String[] args) 
      {
       Method m = new Method();
       m.m2();
      }
     }

    Output:

    This is method m2
    This is method m1


  • Java example of Inner Class

    In this tutorial, we will write an inner class program in java. Before that, you should have knowledge on the following topic in Java.


    Example of Inner class in Java

    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


    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:

    I am Inner Class


  • Example of Constructor in Java

    In this tutorial, we will write a constructor program in java. Before that, you should have knowledge on the following topic in Java.


    Constructor program in Java

    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


    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


  • Java Program for Super keyword

    In this tutorial, we will write a program in java for the use of super keyword. Before that, you should have knowledge on the following topic in Java.


    Java Program for Super keyword

    Example of a super keyword to differentiate the members of the superclass from a subclass.

    class SuperClass
    {
      int id = 20;
      public void display()
      {
        System.out.println("Super Class display method");
      }
    }
    
    public class SubClass extends SuperClass
    {
      int id = 10;
      public void display()
      {
        System.out.println("Sub Class display method");
      }
    
      public void myMethods()
      {
        // Instantiating subclass
        SubClass s = new SubClass();
    
        // display method and value of sub class
        s.display();
        System.out.println("Sub Class id:" + s.id);
    
        // display method and value of super class using super
        super.display();
        System.out.println("Super Class id::" + super.id);
      }
    
      public static void main(String args[])
      {
        SubClass sub = new SubClass();
        sub.myMethods();
      }
    }

    Output:

    Base Class display method
    Sub Class id:10
    Super Class display method
    Super Class id::20


  • Inheritance Example in Java

    In this tutorial, we will write an Inheritance program in java. Before that, you should have knowledge on the following topic in Java.


    Basic Example for Inheritance:

    class Dog 
     {
      void dogName() 
      {
       System.out.println("My Name is Bruno");
      }
     }
    
     class Breed extends Dog 
     {
       void myBreed() 
       {
        System.out.println("German Shepard");
       }
     }
    
     public class Main 
     {
      public static void main(String args[]) 
      {
      Breed d = new Breed();
      d.dogName();
      d.myBreed();
      }
     }

    Output:

    My Name is Bruno
    German Shepard


    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:

    Super class method
    Base class method


    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:

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


    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:

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


  • Polymorphism Example in Java

    In this tutorial, we will write a polymorphism program in java. Before that, you should have knowledge on the following topic in Java.


    1. 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. 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();	// Dog reference and object
        Dog b = new breed(); // breed reference but Dog object
    
        d.display();	// runs the method in Dog class
        b.display();	// runs the method in Dog class
      }
    }

    Output:

    I am A Dog
    Breed: German Shepard


  • Encapsulation Example in java

    In this tutorial, we will write an encapsulation program in java. Before that, you should have knowledge on the following topic in Java.


    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


  • Example of Abstraction in Java

    In this tutorial, we will write a java program to demonstrate abstraction. Before that, you should have knowledge on the following topic in Java.


    Example of Abstraction in Java

    Source code: Example of abstract class in java:

    // 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


  • Example of Method Overriding and Overloading in Java

    In this tutorial, we will write a program for method overriding and method overloading. Before that, you should have knowledge on the following topic in Java.


    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 Main
     {
    
        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:

    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.


    1. Method overloading by changing the data type of Arguments

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

    Output:

    sum is 10
    sum is 11.0


    2. Method overloading by changing the number of the argument

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

    Output of Method overloading:

    Argument List is empty

    Name:Karan Id:1101

    Name:Prashant Id:1102 Age:23