Object Oriented Programming In Java - Java Tutorial 2020 - Java Programming Tutorial @ Fresher-Naukri.com

Object Oriented Programming In Java


Object-Oriented Programming In Java

OOPs Concepet In Java: the main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

OOPs Concepts:
  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
  • Class
  • Object
  • Method
  • Message Passing
Polymorphism:

Polymorphism is a OOPS concept where one name can have many forms for example, you have a smartphone for communication. The communication mode you choose could be anything.It can be a call, a text message, a picture message, mail, etc. So, the goal is common that is communication, but their approach is different. This is called Polymorphism.

public class Sum  {

       public int sum(int x, int y)
       {
              return (x + y);
        }

        public int sum(int x, int y, int z)
        {
               return (x + y + z);
         }
           
         public double sum(double x, double y)
         {
                  return (x + y);
          }

          public static void main(String args[ ])
          {
                  Sum s = new Sum( );
                  System.out.println(s.sum(5, 6));
                  System.out.println(s.sum(10.5 20.5));
           }
   }  


Output:

11
31.0

Inheritance:

In this tutorial, we will learn about inheritance in Java with the help of examples.Inheritance is one of the key features of OOP (Object-oriented Programming) that allows us to define a new class from an existing class. For example,

class Animal
{

}
class Dog extends Animal
{

}

In Java, we use the extends keyword to inherit from a class. Here, we hava inherited the Dog class from the Animal class.

The Animal is the superclass(parent class or base class), and the Dog is a subclass (child class or derived class). The subclass inherits the fields and methods of the superclass.

Is-a relationship

Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is present between the two classes.

Here are some examples:
  • A car is a vehicle.
  • Orange is a fruit.
  • A surgeon is a doctor.
  • A dog is an animal.
Java Inheritance


class Animal  {

     public void eat( )  {
          System.out.println("I can eat");
      }

     public void sleep( )  {
            System.out.println("I can sleep");
      }

}

class Dog extends Animal  {
     public void bark( )  {
           System.out.println("Ican bark");
      }
}

class  Main  {
       public static void main(string[ ] args)  {

               Dog dog1 = new Dog( );

                dog1.eat( );
                dog1.sleep( );

                dog1.bark( );
         }
    }

Output:

I can eat
I can sleep
i can bark

Here, we have inherited a subclass Dog from superclass Animal. The Dog class inherits the methods eat( ) and sleep( ) from the Animal class.

Hence, objects of the Dog class can access the members of both the Dog class and the Animal class.


Protected Keyword

  • private members can be accessed only within the class
  • public members can be accessed from anywhere

You can also assign methods and fields protected. Protected members are accessble

  • from within the class
  • within its subclasses
  • within the same package
Protected Keyword

class Animal  {
      protected string type;
      private string color;

      public void eat( )  {
           System.out.println("I can eat");
      }

      public void sleep( )  {
            System.out.println("I can eat");
      }

      public string grtColor( ){
           return color;
      }

      public void setColor(String col){
             color = col;
      }
}


class Dog extends Animal  {

     public void displayInfo(String c) 
                        {
            System.out.println("I am  " + type);
            System,out.println("My color is " + c);
              }
     public void bark( ) 
               {
            system.out.println("I can bark");
 }

Output:

I can eat 
I can sleep
I can bark
I am a mammal
My color is black

Here, the type field inside the Animal class is protected. We have accessed this field from the Main class using

  dog1.type = "mammal";

It is possible because both the Animal and Main classes are in the same package(same file).


Java Method Overriding

From the above examples, we know that objects of a subclass can also access methods of its Super class.

What happens if the same method is defined in both the super class and subclass?

Well, in that case, the method in the subclass overrides the method in the super class.


Method Overriding Example

class Animal  {
      protected String type = "animal";

      public void eat( )  {
           System.out.println("I can eat");
       }
  }

class Dog extends Animal  {

       @Override
        public void eat( )  { 
             System.out.println("I eat dog food");
        }

        public void bark( )  {
              System.out.println("I can bark");
       }
}

class Main  {
       public static void main(string[ ] args)  {

             Dog dog1 = new Dog( );
             dog1.eat( );

Output:

I eat dog food
I can sleep
I can bark

Here, eat( ) is present in both the super class animal and subclass dog. We created an object dog1 of the subclass dog.

When we call eat( ) using the dog1 object, the method inside the Dog is called, and the same method of the super class is not called. This is called method overriding.

In the above program, we have used the @override annotation to tell the compiler that we are overriding a method. However, it's not mandatory. We will learn about method overriding in detail in the next tutorial.

If we need to call the eat( ) method of Animal from its sub classes, we use the super keyword


With Super Keyword


class Animal  {
     public Animal( )  {
          System.out.println("I am Animal");
     }

     public void eat( )  {
          System.out.println('I can eat");
     }
}

class Dog extends Animal  {
     public Dog( ){
          super( );
          System.out.println(" I am a dog");
      }

      @Overeide

       public void eat( )  {
            super.eat( );
            system.out.println("I eat dog food");
        }

         public void bark( )  {

              system.out.println("I van bark");
         }
  }

   class Main  {

        public ststic void main(string[ ] args)  {


Output:



I am an Animal

I am a dog 
I can eat
I eat dog food
I can bark

Here, we have used the super keyword to call the constructor using super.eat(). Also, we have called the eat( ) method of Animal superclass using super.eat( ).


Note the difference in the use of super while calling constructor and method. To learn more, visit the Java super keyword.



Inheritance Types :



  • There are five types of inheritance.
  • Single inheritance - Class B extends from class A only.
  • Multilevel inheritance - Class B extends from class A; then class C extends from class B.
  • Hierarchical inheritance - Class A acts as the superclass for classes B, C, and D.
  • Multiple inheritance - Class C extends from interface A and B.
  • Hybrid inheritance - Mix of two or more types of inheritance.

NOTE : Java doesn't support multiple and hybrid inheritance through classes. However,
we can achieve multiple inheritance in Java through interfaces. We will learn about interfaces in later chapters.


Encapsulation 


Encapsulation in Java is a mechanism of wrapping the date and code acting on the date together as a sing unit. In encapsulation, the variables of a class will be hidden from other class, and can be accessed only through the methods of their current class.


Example Encapsulation 


public class EncapTest  { 

     private string name;
     private string idNum;
     private int age;

public int getAge( )  { 

    return age;
  }


public string getName( )  {

      return name;

 }


public string getIdNum( )  {

     return IdNum;
 }


public void setAge( int newAge)  {

    age = newAge;

}


public void setName(string newName)  {

    name = newName;

}


public void setIdNum( string newId)  {

     idNum = newId;

}


The public setXXX() and getXXX() methods are the access points of the instance variables of the  EncapTest class. Normally, these methods are referred to as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters. The variables of the EncapTest class can be accessed using the following program


public class RunEncap   {


     public static void main(String args[ ])  {

         EncapTest encap = new EncapTest( );
         encap.setName("james");
         encap.setAge(20);
         encap.setIdNum("12343ms");

         system.out.print("Name : " + encap.getName( ) + " Age : " + encap.getAge( ) );


        }

}


Output:



Name : James Age : 20 



Abstract 

Abstract is one the import concept in OOPs. Abstraction is a process of hiding the implementation details and showing only functionality to the user,

Abstract Example

abstract class Sum{

       public abstract int sum of Two(int n1, int n2);
       public abstract int sum of Three(int nl, int n2, int n3);

       public void disp( )  {
              System,out.println("Method of class Sum");

       }
}

class Demo extends Sum{

       public int sumOfTwo(int num1, int num2) {
               return num1+num2;

        }
       public int sumOfThree(int num1, int num2, int num3) {
             return num1+num2+num3;

        }
        public static void main(String args[ ] )  {
               Sum obj = new Demo( ) ;
               System.out.println(obj.sumOfTwo(3, 7) ) ;
               System.out.println(obj.sumOfThree(4, 3, 19) ) ;
               obj.disp( );

        }

}


Output:


10
26
Method of class Sum

         
      
  






0 comments 10:

Post a Comment