top
April flash sale

Search

Java Tutorial

The primary ideas behind Java's Object-Oriented Programming are OOP concepts in Java. They are an abstraction, inheritance, encapsulation, and polymorphism. It is essential to understand how Java operates to grasp them. Java OOP ideas basically allow us to generate methods and variables and then reuse them all or a portion of them without compromising safety. There are 4 main OOP concepts in Java. These are: Abstraction:  Abstraction means the use of simple things to represent complexity. We all know how to turn on the television, but we don't have to know how it works to appreciate it. Java abstraction means that simple things like objects, classes, and variables have more complex underlying code and data. This is vital because it makes it possible to avoid repeating the same task countless times. Encapsulation: This is the practice of maintaining variables that are private in class, then making them accessible through public methods. It is a protective barrier that safeguards information and code within the class itself. This allows us to reuse objects or variables without enabling open access to the entire data system. Inheritance: This is an object-oriented uniqueprogramming  function in Java. It allows programmers to generate new classes that share some of the current class attributes. Without reinventing the wheel, this allows us to build on the prior job. Polymorphism: This notion of Java OOP allows programmers to use the same term in distinct situations to mean different things. One type of Java polymorphism is the overloading method. That’s when different meanings are implied by the code itself. The other type is method overriding. That’s when the different meanings are implied by the values of the supplied variables. 1. Abstraction in java Abstraction as an OOP notion in Java works by creating helpful, reusable instruments for programmers. A programmer, for instance, can generate various kinds of objects. These can be variables, functions, or data structures. Programmers can also create different classes of objects. These are ways to define the objects. For example, a class of variables might be an address. The class might specify that each address object shall have a name, street, city, and pin code. The objects, in this case, might be student addresses, citizen addresses, or seller addresses. 2. Encapsulation in java Encapsulation allows us to reuse features without compromising safety. It's a strong Java OOP idea because it saves us a lot of time. For instance, we can generate a piece of code that calls from a database of particular information. Reusing that code with other databases or procedures may be helpful. Encapsulation allows us to do this while maintaining the privacy of our initial information. It also allows us to change our initial code without violating it for others who have already embraced it 3. Inheritance in java Inheritance is another notion of Java OOP that saves work. It operates by allowing another class to embrace/inherit another's class characteristics. We call this a subclass or a child class. The parent is frequently called the base/parent class. To establish a subclass that inherits characteristics from a parent class, we use the keyword extends. 4. Polymorphism in java Java polymorphism operates by using a parent class reference to influence a child's object. By expanding the "animal" class, we could generate a class called "horse." This class could also inherit the class of "professional racing." The "horse" class is "polymorphic" because it inherits the "animal" and "professional racing" class characteristics. 2 more instances of Java polymorphism are overriding methods and overloading methods. Method overriding: The child class can use the notion of OOP polymorphism to override a method of its parent class in method overriding. This enables a programmer to use one method in distinct ways based on whether a parent class object or a child class object invokes it. Method overloading: In method overloading, depending on the context in which it is called, a single method can conduct distinct tasks. That is, depending on what arguments are passed on to it, a single method name could operate in distinct ways. 5. extends keyword in java The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child class) - the class that inherits from another class superclass (parent class) - the class being inherited from To inherit from a class, use the extends keyword. A class is final if it uses a final keyword in the class declaration. Final classes cannot be extended. In Java, EVERY class is a subclass of java.lang.Object. // Below is an example of extending a class class A {  int x = 0;  void f1 () { x = x+1;}  }  class B extends A {}  public class Test1 {  public static void main(String[] args) {  A b = new A();          b.f1();          System.out.println( b.x ); // It prints 1      }  } 6. final keyword in java We can use the final keyword in different ways. The final is a non-access modifier that only applies to a variable, a method or a class. There are various contexts in which the final is used. The final variable is nothing but a constant. Once it is initialized, we cannot alter the value of a final variable It is not possible to override a final method. This means that even if a sub-class can call the parent class ' final method without any problems, it cannot override it. We can't extend the final class. Points to Remember in case of final keyword: It is not possible to override a final method.There is no inheritance of a final class. If the method parameters are declared final then it is not possible to change the value of these parameters. We cannot make constructor as final. The local final variable must be initialized during declaration.  All variables inside an interface are final by default.  We can't alter a final variable's value. Naming the final variable in all CAPS is the best practice.  Finalize, final, finally are 3 different keywords in java. finally is used in the exception handling framework and finalize is a special method that is called by JVM during garbage collection. 7. super keyword in java Super is a Java keyword that relates to a class's instant parent and is used to call a method specified in the superclass within the subclass procedure definition. It is impossible to call a superclass with method as private. The keyword super can only call the methods that are public and protected. It is also used by class constructor to invoke parent class constructors. Syntax: super.<method-name>(); Usage of Java super Keyword super keyword can be used to invoke immediate parent class method. super keyword can be used to refer immediate parent class instance variable. super() can be used to call immediate parent class constructor. 8. Covariant return type in java By altering the return type, it was not feasible to override a method before JDK 5.0. The name, argument types and return type of the overriding method in child class must be precisely the same as that of the parent class method when overriding a parent class method. The overriding method of return type was said to be invariant. In Java 5.0 onward it is possible to have different types of return in child class for an overriding method, but the type of return of the child should be the subtype of the return type of the parent. With regard to the return type, the overriding technique becomes variant. // Java program to show below that we can have different return types in java program if the return type in the overridden method is sub-type.// Two classes used for return types are below:  class SuperClass {}   class SubClass extends SuperClass {}   class Parent   {   SuperClass fun()   {   System.out.println("Parent class");   return new SuperClass();   }   }   class Child extends Parent {   SubClass fun()   {   System.out.println("Child class");   return new SubClass ();   }   }   public class Main   {   public static void main(String args[])   {   Parent parent = new Parent ();   parent.fun();   Child child = new Child ();   child.fun();   }   } Output: Parent class  Child class 9. Method overriding in java Overriding is a characteristic in any object-oriented programming language that enables a subclass or child class to specifically implement a method already supplied by one of its superclasses or parent classes. Usage of Java Method Overriding Method overriding is used to specifically implement a method already supplied by its superclass. The overriding method is used for polymorphism during runtime. Rules for Java Method Overriding The method must have the same name as in the base class The method must have the same parameter as in the base class. There must be an IS-A relationship between base and child class. (inheritance). //Creating a base class.   class Vehicle{   //defining a method   void run(){System.out.println("Vehicle is running");}   }   //Creating a subclass   class Scooter extends Vehicle{   //defining the same method as in the parent class   void run(){     System.out.println("Scooter is running safely");    }   publicstaticvoid main(String args[]){   Scooter obj = new Scooter ();  obj.run();//calling method   }   } Output: Scooter is running safely 10. Interface in java An interface can have methods and variables like a class, but the methods declared in the interface are abstract by default (only signature of the method, nobody). Interfaces indicate what to do and not how to do a class. This is the class's blueprint. An Interface is about capabilities; like a Player may be an interface; and any class implementing Player must be able to (or must implement) move().  It indicates a set of methods to be implemented by the class. If a class implements an interface and does not provide method bodies for all functions specified in the interface, then class must be declared abstract. Comparator Interface is an instance of a Java library. If this interface is implemented by a class, it can be used to sort a collection. Use the keyword interface to declare an interface. It is used to give complete abstraction. This implies that all interface methods are stated with empty bodies and are public and by default, all fields are public, static and final. A class that implements an interface must implement all the methods declared in the interface. To implement any interface in java we use implements keyword. Why do we use interface in java? We achieve loose coupling in java using interface. abstract classes may contain non-final variables, whereas variables in an interface are final, public and static. It also provides a total abstraction. As we know java does not support multiple inheritances in the case of class, however by using interface we can achieve multiple inheritance. Syntax to declare interface: interface <interface_classname> {      // declare constant variables      // declare methods that abstract       // by default  } Aggregation in java If a class has a reference to an entity, it is called an aggregation. Aggregation is the connection of HAS-A. Consider a situation, Employee object contains many pieces of information such as id, name, email Id, etc. It contains one more object named address, which contains its own information such as city, state, country, zip code, etc. as given below. class Employee{    int id;    String name;    Address address;//Address is a class    ...    } An employee has an entity reference address in such a case, so a relationship is the address of Employee HAS-A. We use aggregation for code reusability. The composition is an aggregation situation in particular. A limited aggregation is called composition in a more particular way. If an object contains the other object, it is called composition if the contained object cannot occur without the presence of a container object. Example: There is a class that includes students. There can't be a student without a class. Composition occurs between classes and students.The composition is more restrictive in nature. The composed object cannot exist without the other object when there is a composition between two objects.  There's no such limitation in aggregation. Although one object may contain the other object, the composed object does not have to exist. The composed object's presence is completely optional. There is a need for direction in both aggregation and composition. The direction specifies which object the other object includes. Example: Students and books are included in a library. Library-student relationship is aggregation. The library-book relationship is composition. A student can exist without a library and therefore it is aggregation. Without a library, a student can exist and is therefore an aggregation. Without a library, a book cannot exist and is, therefore, a composition. I'm choosing this instance for simple comprehension. Don't go deeper into relationships and justify them! 
logo

Java Tutorial

Object Oriented Concepts

The primary ideas behind Java's Object-Oriented Programming are OOP concepts in Java. They are an abstraction, inheritance, encapsulation, and polymorphism. It is essential to understand how Java operates to grasp them. Java OOP ideas basically allow us to generate methods and variables and then reuse them all or a portion of them without compromising safety. 

There are 4 main OOP concepts in Java. These are: 

  • Abstraction:  Abstraction means the use of simple things to represent complexity. We all know how to turn on the television, but we don't have to know how it works to appreciate it. Java abstraction means that simple things like objects, classes, and variables have more complex underlying code and data. This is vital because it makes it possible to avoid repeating the same task countless times. 
  • Encapsulation:This is the practice of maintaining variables that are private in class, then making them accessible through public methods. It is a protective barrier that safeguards information and code within the class itself. This allows us to reuse objects or variables without enabling open access to the entire data system. 
  • Inheritance: This is an object-oriented uniqueprogramming  function in Java. It allows programmers to generate new classes that share some of the current class attributes. Without reinventing the wheel, this allows us to build on the prior job. 
  • Polymorphism:This notion of Java OOP allows programmers to use the same term in distinct situations to mean different things. One type of Java polymorphism is the overloading method. That’s when different meanings are implied by the code itself. The other type is method overriding. That’s when the different meanings are implied by the values of the supplied variables. 

1. Abstraction in java 

Abstraction as an OOP notion in Java works by creating helpful, reusable instruments for programmers. A programmer, for instance, can generate various kinds of objects. These can be variables, functions, or data structures. Programmers can also create different classes of objects. These are ways to define the objects. 

For example, a class of variables might be an address. The class might specify that each address object shall have a name, street, city, and pin code. The objects, in this case, might be student addresses, citizen addresses, or seller addresses. 

2. Encapsulation in java 

Encapsulation allows us to reuse features without compromising safety. It's a strong Java OOP idea because it saves us a lot of time. For instance, we can generate a piece of code that calls from a database of particular information. Reusing that code with other databases or procedures may be helpful. Encapsulation allows us to do this while maintaining the privacy of our initial information. It also allows us to change our initial code without violating it for others who have already embraced it 

3. Inheritance in java 

Inheritance is another notion of Java OOP that saves work. It operates by allowing another class to embrace/inherit another's class characteristics. We call this a subclass or a child class. The parent is frequently called the base/parent class. To establish a subclass that inherits characteristics from a parent class, we use the keyword extends. 

4. Polymorphism in java 

Java polymorphism operates by using a parent class reference to influence a child's object. By expanding the "animal" class, we could generate a class called "horse." This class could also inherit the class of "professional racing." The "horse" class is "polymorphic" because it inherits the "animal" and "professional racing" class characteristics. 

2 more instances of Java polymorphism are overriding methods and overloading methods. 

  • Method overridingThe child class can use the notion of OOP polymorphism to override a method of its parent class in method overriding. This enables a programmer to use one method in distinct ways based on whether a parent class object or a child class object invokes it. 
  • Method overloading: In method overloading, depending on the context in which it is called, a single method can conduct distinct tasks. That is, depending on what arguments are passed on to it, a single method name could operate in distinct ways. 

5. extends keyword in java 

The extends keyword extends a class (indicates that a class is inherited from another class). 

In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: 

  • subclass (child class) - the class that inherits from another class 
  • superclass (parent class) - the class being inherited from 

To inherit from a class, use the extends keyword. 

A class is final if it uses a final keyword in the class declaration. Final classes cannot be extended. 

In Java, EVERY class is a subclass of java.lang.Object. 

// Below is an example of extending a class 
class A      int x = 0; 
     void f1 () { x = x+1;} 
} 
class B extends A {} 

public class Test1    public static void main(String[] args) { 
A b = new A(); 
        b.f1(); 
        System.out.println( b.x ); // It prints 1 
    } 
} 

6. final keyword in java 

We can use the final keyword in different ways. The final is a non-access modifier that only applies to a variable, a method or a class. There are various contexts in which the final is used. 

 final keyword in java

The final variable is nothing but a constant. Once it is initialized, we cannot alter the value of a final variable 

It is not possible to override a final method. This means that even if a sub-class can call the parent class ' final method without any problems, it cannot override it. 

We can't extend the final class. 

Points to Remember in case of final keyword: 

It is not possible to override a final method.There is no inheritance of a final class. If the method parameters are declared final then it is not possible to change the value of these parameters. 

We cannot make constructor as final. The local final variable must be initialized during declaration.  All variables inside an interface are final by default.  We can't alter a final variable's value. Naming the final variable in all CAPS is the best practice.  Finalize, final, finally are 3 different keywords in java. finally is used in the exception handling framework and finalize is a special method that is called by JVM during garbage collection

7. super keyword in java 

Super is a Java keyword that relates to a class's instant parent and is used to call a method specified in the superclass within the subclass procedure definition. It is impossible to call a superclass with method as private. The keyword super can only call the methods that are public and protected. It is also used by class constructor to invoke parent class constructors. 

Syntax: super.<method-name>(); 

Usage of Java super Keyword 

  • super keyword can be used to invoke immediate parent class method. 
  • super keyword can be used to refer immediate parent class instance variable. 
  • super() can be used to call immediate parent class constructor. 

8. Covariant return type in java 

By altering the return type, it was not feasible to override a method before JDK 5.0. The name, argument types and return type of the overriding method in child class must be precisely the same as that of the parent class method when overriding a parent class method. The overriding method of return type was said to be invariant. 

In Java 5.0 onward it is possible to have different types of return in child class for an overriding method, but the type of return of the child should be the subtype of the return type of the parent. With regard to the return type, the overriding technique becomes variant. 

// Java program to show below that we can have different return types in java program if the return type in the overridden method is sub-type.
// Two classes used for return types are below:  

class SuperClass {}  
class SubClass extends SuperClass {}  
class Parent  
{  
SuperClass fun()  
{  
System.out.println("Parent class");  
return new SuperClass();  
}  
}  
class Child extends Parent 
{  
SubClass fun()  
{  
System.out.println("Child class");  
return new SubClass ();  
}  
}  
public class Main  
{  
public static void main(String args[])  
{  
Parent parent = new Parent ();  
parent.fun();  
Child child = new Child ();  
child.fun();  
}  
} 

Output: 

Parent class 
Child class 

9. Method overriding in java 

Overriding is a characteristic in any object-oriented programming language that enables a subclass or child class to specifically implement a method already supplied by one of its superclasses or parent classes. 

Usage of Java Method Overriding 

  • Method overriding is used to specifically implement a method already supplied by its superclass. 
  • The overriding method is used for polymorphism during runtime. 

Rules for Java Method Overriding 

  • The method must have the same name as in the base class 
  • The method must have the same parameter as in the base class. 
  • There must be an IS-A relationship between base and child class. (inheritance). 
//Creating a base class.  
 
class Vehicle{   
  //defining a method   
void run(){System.out.println("Vehicle is running");}   
}
   
//Creating a subclass
  
class Scooter extends Vehicle{   
  //defining the same method as in the parent class   
void run(){ 
   System.out.println("Scooter is running safely"); 
  }
   
publicstaticvoid main(String args[]){   
  Scooter obj = new Scooter (); 
  obj.run();//calling method   
  }   
}   

Output: 

Scooter is running safely 

10. Interface in java 

An interface can have methods and variables like a class, but the methods declared in the interface are abstract by default (only signature of the method, nobody). 

  • Interfaces indicate what to do and not how to do a class. This is the class's blueprint. 
  • An Interface is about capabilities; like a Player may be an interface; and any class implementing Player must be able to (or must implement) move().  It indicates a set of methods to be implemented by the class. 
  • If a class implements an interface and does not provide method bodies for all functions specified in the interface, then class must be declared abstract. 
  • Comparator Interface is an instance of a Java library. If this interface is implemented by a class, it can be used to sort a collection. 

Use the keyword interface to declare an interface. It is used to give complete abstraction. This implies that all interface methods are stated with empty bodies and are public and by default, all fields are public, static and final. A class that implements an interface must implement all the methods declared in the interface. To implement any interface in java we use implements keyword. 

Why do we use interface in java? 

  • We achieve loose coupling in java using interface. 
  • abstract classes may contain non-final variables, whereas variables in an interface are final, public and static. 
  • It also provides a total abstraction. 
  • As we know java does not support multiple inheritances in the case of class, however by using interface we can achieve multiple inheritance. 

Syntax to declare interface: 

interface <interface_classname> { 
    // declare constant variables 
    // declare methods that abstract  
    // by default 
} 
  • Aggregation in java 

If a class has a reference to an entity, it is called an aggregation. Aggregation is the connection of HAS-A. 

Consider a situation, Employee object contains many pieces of information such as id, name, email Id, etc. It contains one more object named address, which contains its own information such as city, state, country, zip code, etc. as given below. 

class Employee{   
int id;   
String name;   
Address address;//Address is a class   
...   
} 

An employee has an entity reference address in such a case, so a relationship is the address of Employee HAS-A. 

We use aggregation for code reusability. 

The composition is an aggregation situation in particular. A limited aggregation is called composition in a more particular way. If an object contains the other object, it is called composition if the contained object cannot occur without the presence of a container object. 

Example: There is a class that includes students. There can't be a student without a class. Composition occurs between classes and students.The composition is more restrictive in nature. The composed object cannot exist without the other object when there is a composition between two objects.  

There's no such limitation in aggregation. Although one object may contain the other object, the composed object does not have to exist. The composed object's presence is completely optional. There is a need for direction in both aggregation and composition. The direction specifies which object the other object includes. 

Example: Students and books are included in a library. Library-student relationship is aggregation. The library-book relationship is composition. A student can exist without a library and therefore it is aggregation. Without a library, a student can exist and is therefore an aggregation. Without a library, a book cannot exist and is, therefore, a composition. I'm choosing this instance for simple comprehension. Don't go deeper into relationships and justify them! 

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

protective orders in virginia

Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.

Johnfrance

Thank you for your valuable information.

sam

Thank you for this wonderful article!

Belay Abera

This article was really helpful to me, thank you!

dfsdf

super article!