Showing posts with label Java OOPs. Show all posts
Showing posts with label Java OOPs. Show all posts

Monday, September 12, 2022

Spring Boot – Difference Between AOP and OOP

Spring Boot, AOP, OOP, Oracle Java Certification, Oracle Java Career, Java Skills, Java Jobs, Java Tutorial and Materials, Java Prep, Java Preparation

AOP(Aspect-Oriented Programming) complements OOP by enabling modularity of cross-cutting concerns. The Key unit of Modularity(breaking of code into different modules) in Aspect-Oriented Programming is Aspect. one of the major advantages of AOP is that it allows developers to concentrate on business logic. It is more convenient to use because changes need to be done in only one place. AOP is used along with spring Ioc to provide a very capable middleware solution.

Note: Cross cutting concerns are one of the concerns in any application such as logging, security, caching, etc. They are present in one part of the program but they may affect other parts of the program too.

Spring Boot, AOP, OOP, Oracle Java Certification, Oracle Java Career, Java Skills, Java Jobs, Java Tutorial and Materials, Java Prep, Java Preparation
AOP is used along with Oop as it also works around classes and objects, etc. We can also say that Oop is a basic term for AOP. Different Frameworks used in Aop are AspectJ, JBoss, and Spring. AOP makes the program loosely coupled. AOP separates business logic from cross-cutting concerns. The aspect class which contains cross-cutting concerns is annotated by @Aspect and @EnableAspectJAutoProxy annotations

AOP has different terms like Aspect, Weaving, different types of advices, JoinPoints and Pointcut expressions, etc. These terms are explained below:

◉ Aspect: The cross-cutting concerns are modularized as Aspect. The classes which contain such cross-cutting concerns are annotated with @Aspect annotation.
◉ Join point: Method execution is represented by using Joinpoint.
◉ Advice: Aspect takes action on a particular Joinpoint. This action depends on various advice which is explained below:
◉ Before advice: It runs before the method execution.
◉ After returning advice: It runs after the result is returned by the method.
◉ After throwing advice: It runs after an exception is thrown by the method.
◉ After (finally) advice: It is executed after method execution or after an exception is thrown or the result is returned by the method.
◉ Around advice: It can perform the behavior before and after the method invocation.
◉ Pointcut: Pointcut is a signature that matches the join points.

Illustration: A pointcut expression with before advice:

// Annotation
@Before("execution(* abc.efg.gettingstarted.dao.*.add(..))")

public void allMethods(Point Point) 
{  // Aspect body }

Object-Oriented Programming


The object-oriented programming model works around classes and objects. The main building blocks of Oop are classes, objects, methods, attributes, etc. Oop has various advantages such as code reusability, flexibility, etc. It also maintains modularity using classes.

Note: Object is an instance of class and class is a blueprint of an object created.

The Key unit of Modularity(breaking of code into different modules) in Object-Oriented Programming is class. Oop contains objects, classes, interfaces, etc. Oop lacks the feature of using cross-cutting concerns. It consists of various concepts such as Data abstraction, Encapsulation, Polymorphism, and Inheritance.

Illustration: If there is a fruit class then apple, orange, banana are various objects of the fruit class.

Source: geeksforgeeks.org

Friday, August 13, 2021

Four Main Object Oriented Programming Concepts of Java

Object Oriented Programming Concepts of Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Career, Core Java, Oracle Java OOP

Object-oriented programming generally referred to as OOPS is the backbone of java as java being a completely object-oriented language. Java organizes a program around the various objects and well-defined interfaces. There are four pillars been here in OOPS which are listed below. These concepts aim to implement real-world entities in programs.

◉ Abstraction

◉ Encapsulation

◉ Inheritance

◉ Polymorphism

Abstraction is a process of hiding implementation details and exposes only the functionality to the user. In abstraction, we deal with ideas and not events. This means the user will only know “what it does” rather than “how it does”.

There are two ways to achieve abstraction in Java

1. Abstract class (0 to 100%)

2. Interface (100%)

Real-Life Example: A driver will focus on the car functionality (Start/Stop -> Accelerate/ Break), he/she does not bather about how the Accelerate/ brake mechanism works internally. And this is how the abstraction works.

Certain key points should be remembered regarding this pillar of OOPS as follows:

◉ The class should be abstract if a class has one or many abstract methods

◉ An abstract class can have constructors, concrete methods, static method, and final method

◉ Abstract class can’t be instantiated directly with the new operator. It can be possible as shown in pre tag below:

A b = new B();

◉ The child class should override all the abstract methods of parent else the child class should be declared with abstract keyword

Object Oriented Programming Concepts of Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Career, Core Java, Oracle Java OOP

Example:

// Abstract class
public abstract class Car {
public abstract void stop();
}

// Concrete class
public class Honda extends Car {
// Hiding implementation details
@Override public void stop()
{
System.out.println("Honda::Stop");
System.out.println(
"Mechanism to stop the car using break");
}
}

public class Main {
public static void main(String args[])
{
Car obj
= new Honda(); // Car object =>contents of Honda
obj.stop(); // call the method
}
}

Pillar 2: Encapsulation


Encapsulation is the process of wrapping code and data together into a single unit.

Real-Life Example:

A capsule which is mixed of several medicines. The medicines are hidden data to the end user.

In order to achieve encapsulation in java follow certain steps as proposed below:

◉ Declare the variables as private
◉ Declare the setters and getters to set and get the variable values

Note: There are few disadvantages of encapsulation in java as follows:

1. Control Over Data: We can write the logic in the setter method to not store the negative values for an Integer. So by this way we can control the data.
2. Data Hiding: The data members are private so other class can’t access the data members.
3. Easy to test: Unit testing is easy for encapsulated classes

Example:

// AJavaclasswhichisafullyencapsulatedclass.
publicclass Car
{
// privatevariable
privateStringname;
// gettermethodforname
publicStringgetName()
{
returnname;
}
// settermethodforname
publicvoidsetName(Stringname)
{
this.name = name
}
}

// Javaclasstotesttheencapsulatedclass.
public class Test
{
publicstaticvoidmain(String[]args)
{
// creatinginstanceoftheencapsulatedclass
Carcar
= newCar();
// settingvalueinthenamemember
car.setName("Honda");
// gettingvalueofthenamemember
System.out.println(car.getName());
}
}

Pillar 3: Inheritance


Inheritance is the process of one class inheriting properties and methods from another class in Java. Inheritance is used when we have is-a relationship between objects.  Inheritance in Java is implemented using extends keyword.

Real-life Example:

The planet Earth and Mars inherits the super class Solar System and Solar system inherits the Milky Way Galaxy. So Milky Way Galaxy is the top super class for Class Solar System, Earth and Mars.

Let us do discuss the usage of inheritance in java applications with a generic example before proposing the code. So consider an example extending the Exception class to create an application-specific Exception class that contains more information like error codes. For example NullPointerException.

There are 5 different types of inheritance in java as follows:

1. Single Inheritance: Class B inherits Class B using extends keyword

2. Multilevel Inheritance: Class C inherits class B and B inherits class A using extends keyword

3. Hierarchy Inheritance: Class B and C inherits class A in hierarchy order using extends keyword

4. Multiple Inheritance: Class C inherits Class A and B. Here A and B both are superclass and C is only one child class. Java is not supporting Multiple Inheritance, but we can implement using Interfaces.

5. Hybrid Inheritance: Class D inherits class B and class C. Class B and C inherits A. Here same again Class D inherits two superclass, so Java is not supporting Hybrid Inheritance as well.

Example:

// super class
class Car {
// the Car class have one field
public String wheelStatus;
public int noOfWheels;

// the Car class has one constructor
public Car(String wheelStatus, int noOfWheels)
{
this.wheelStatus = wheelStatus;
this.noOfWheels = noOfWheels;
}

// the Car class has three methods
public void applyBrake()
{
wheelStatus = "Stop" System.out.println(
"Stop the car using break");
}

// toString() method to print info of Car
public String toString()
{
return ("No of wheels in car " + noOfWheels + "\n"
+ "status of the wheels " + wheelStatus);
}
}

// sub class
class Honda extends Car {

// the Honda subclass adds one more field
public Boolean alloyWheel;

// the Honda subclass has one constructor
public Honda(String wheelStatus, int noOfWheels,
Boolean alloyWheel)
{
// invoking super-class(Car) constructor
super(wheelStatus, noOfWheels);
alloyWheel = alloyWheel;
}

// the Honda subclass adds one more method
public void setAlloyWheel(Boolean alloyWheel)
{
alloyWheel = alloyWheel;
}

// overriding toString() method of Car to print more
// info
@Override public String toString()
{
return (super.toString() + "\nCar alloy wheel "
+ alloyWheel);
}
}

// driver class
public class Main {
public static void main(String args[])
{

Honda honda = new Honda(3, 100, 25);
System.out.println(honda.toString());
}
}

Pillar 4: Polymorphism in java 


Polymorphism is the ability to perform many things in many ways. The word Polymorphism is from two different Greek words- poly and morphs. “Poly” means many, and “Morphs” means forms. So polymorphism means many forms. The polymorphism can be present in the case of inheritance also. The functions behave differently based on the actual implementation.

Real-life Example:

A delivery person delivers items to the user. If it’s a postman he will deliver the letters. If it’s a food delivery boy he will deliver the foods to the user. Like this polymorphism implemented different ways for the delivery function.

There are two types of polymorphism as listed below:

1. Static or Compile-time Polymorphism
2. Dynamic or Run-time Polymorphism

Static or Compile-time Polymorphism when the compiler is able to determine the actual function, it’s called compile-time polymorphism. Compile-time polymorphism can be achieved by method overloading in java. When different functions in a class have the same name but different signatures, it’s called method overloading. A method signature contains the name and method arguments. So, overloaded methods have different arguments. The arguments might differ in the numbers or the type of arguments.

Example 1: Static Polymorphism

public class Car{
public void speed() {
}
public void speed(String accelerator) {
}
public int speed(String accelerator, int speedUp) {
return carSpeed;
}
}

Dynamic or Run-time Polymorphism occurs when the compiler is not able to determine whether it’s superclass method or sub-class method it’s called run-time polymorphism. The run-time polymorphism is achieved by method overriding. When the superclass method is overridden in the subclass, it’s called method overriding.

Example 2: Dynamic Polymorphism

import java.util.Random;

class DeliveryBoy {

public void deliver() {
System.out.println("Delivering Item");
}

public static void main(String[] args) {
DeliveryBoy deliveryBoy = getDeliveryBoy();
deliveryBoy.deliver();
}

private static DeliveryBoy getDeliveryBoy() {
Random random = new Random();
int number = random.nextInt(5);
return number % 2 == 0 ? new Postman() : new FoodDeliveryBoy();
}
}

class Postman extends DeliveryBoy {
@Override
public void deliver() {
System.out.println("Delivering Letters");
}
}

class FoodDeliveryBoy extends DeliveryBoy {
@Override
public void deliver() {
System.out.println("Delivering Food");
}
}

Output

Delivering Letters

Source: geeksforgeeks.org

Monday, August 9, 2021

Difference Between Implements and Extends

Java Implements, Java Extends, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Guides, Java Certification

Implements vs Extends

Implements and Extends are two keywords found in Java programming language that provides a means of transferring added functionality to a new class. Implements keyword is used explicitly for implementing an interface, while Extends keyword is used for inheriting from a (super) class. Please note that the concepts of inheritance and interfaces are present in most of the other object oriented programming languages like C# and VB.NET, but they offer different syntax or keywords for applying those concepts. This article only focuses on Implements and Extends keywords defined in Java.

Extends

Extends keyword is used to implement the concept of inheritance in Java programming language. Inheritance essentially provides code reuse by allowing extending properties and behavior of an existing class by a newly defined class. When a new subclass (or derived class) extends a super class (or parent class) that subclass will inherit all attributes and methods of the super class. The subclass can optionally override the behavior (provide new or extended functionality to methods) inherited from the parent class. A subclass cannot extend multiple super classes in Java. Therefore, you cannot use extends for multiple inheritance. In order to have multiple inheritance, you need to use interfaces as explained below.

Implements

Implements keyword in Java programming language is used for implementing an interface by a class. An interface in Java is an abstract type that is used to specify a contract that should be implemented by classes, which implement that interface. Usually an interface will only contain method signatures and constant declarations. Any interface that implements a particular interface should implement all methods defined in the interface, or should be declared as an abstract class. In Java, the type of an object reference can be defined as an interface type. But that object must either be null or should hold an object of a class, which implements that particular interface. Using Implements keyword in Java, you can implement multiple interfaces to a single class. An Interface cannot implement another interface. However an interface can extend a class.

Difference between Implements and Extends

Although, Implements and Extends are two keywords that provide a mechanism to inherit attributes and behavior to a class in Java programming language, they are used for two different purposes. Implements keyword is used for a class to implement a certain interface, while Extends keyword is used for a subclass to extend from a super class. When a class implements an interface, that class needs to implement all the methods defined in the interface, but when a subclass extends a super class, it may or may not override the methods included in the parent class. Finally, another key difference between Implements and Extends is that, a class can implement multiple interfaces but it can only extend from one super class in Java. In general, usage of Implements (interfaces) is considered more favorable compared to the usage of Extends (inheritance), for several reasons like higher flexibility and the ability to minimize coupling. Therefore in practice, programming to an interface is preferred over extending from base classes.

Source: differencebetween.com

Friday, July 30, 2021

Interfaces and Polymorphism in Java

Java Interfaces, Java Polymorphism, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Career, Oracle Java Certification, Oracle Java OOPs

Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, interfaces, etc. In this article, we will discuss polymorphism and interface concepts.

Polymorphism is that it has many forms that mean one specific defined form is used in many different ways. The simplest real-life example is let’s suppose we have to store the name of the person and the phone number of the person, but there are many situations when a person has two different phone numbers. We have to save the same phone number under the same name.

Let us interpret it with help . So, in java, the problem can be solved using an object-oriented concept, void insertPhone(String name, int phone). So, this method is used to save the phone number of the particular person. Similarly, we can use the same form but a different signature means different parameters to store the alternative phone number of the person’s void insertPhone(String name, int phone1, int phone2). One method has two different forms and performs different operations. This is an example of polymorphism, which is method overloading.

Types of polymorphism in Java:

1. Run time polymorphism

2. Compile-time polymorphism

Type 1: Run time polymorphism

This type of polymorphism is resolved by the java virtual machine, not by the java compiler. That’s why this type of polymorphism is called run-time polymorphism. Run time polymorphism occurs during method overriding in java.

Example 

// Java Program to Illustrate Run-time polymorphism

// Importing I/O classes

import java.io.*;

// Class 1 (Parent class)

class GFG1 {

//name method

void name() {

System.out.println("This is the GFG1 class");

}

}

// Class 2 (Chile class)

// Main class extending parent class

public class GFG extends GFG1 {

// Method 1

void name() {

// Print statement

System.out.println("This is the GFG class");

}

// Method 2

// Main drive method

public static void main(String[] args) {

// Now creating 2 objects with different references and

// calling the Method 1 over the objects

// Case 1: GFG1 reference and GFG1 is the object

GFG1 ob = new GFG1();

ob.name();

// Case 2: GFG1 reference and GFG is the object

GFG1 ob1 = new GFG();

ob1.name();

}

}

Output

This is the GFG1 class
This is the GFG class

Output explanation: 

In the above example, the same function i.e name is called two times, but in both cases, the output is different. The signatures of these methods are also the same. That’s why compilers cannot be able to identify which should be executed. This is determined only after the object creation and reference of the class, which is performed during run time (Memory management ). That’s why this is run-time polymorphism.

Type 2: Compile-time polymorphism

Method overloading is an example of the compile-time polymorphism method. Overloading means a function having the same name but a different signature. This is compile-time polymorphism because this type of polymorphism is determined during the compilation time because during writing the code we already mention the different types of parameters for the same function name.

Example 

// Java Program to Illustrate Run-time polymorphism

// Importing required classes
import java.io.*;
import java.util.*;

// Class 1
// Helper class
class First {

// Method of this class
// Without any parameter
void check()
{

// Print statement if this method is called
System.out.println("This is the class First");
}
}

// Class 2
// Main class
class Second extends First {

// Method overloading
void check(String name)
{
// Printing the name of the class method having the
// parameter
System.out.println("This is the class " + name);
}

// Method 2
// Main driver method
public static void main(String args[])
{
// Creating object of class 2
Second ob = new Second();
// Calling method over class 2 object
ob.check("Second");

// Creating object of class 1
First ob1 = new First();
ob.check();

// Upcasting
First ob2 = new Second();
ob.check();
}
}

Output

This is the class Second
This is the class First
This is the class First

Java Interfaces, Java Polymorphism, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Career, Oracle Java Certification, Oracle Java OOPs
Interfaces are very similar to classes. They have variables and methods but the interfaces allow only abstract methods(that don’t contain the body of the methods), but what is the difference between the classes and the interfaces? The first advantage is to allow interfaces to implement the multiple inheritances in a particular class. The JAVA language doesn’t support multiple inheritances if we extend multiple classes in the class, but with the help of the interfaces, multiple inheritances are allowed in Java.

Real-life Example

The real-world example of interfaces is that we have multiple classes for different levels of employees working in a particular company and the necessary property of the class is the salary of the employees and this. We must be implemented in every class and. Also, it is different for every employee here. The concept of the interface is used. We simply create an interface containing an abstract salary method and implement it in all the classes and we can easily define different salaries of the employees.

Example

// Java Program to Demonstarte Concept of interfaces

// Interfacce
interface salary {
void insertsalary(int salary);
}

// Class 1
// Implementing the salary in the class
class SDE1 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary() { System.out.println(this.salary); }
}

// Class 2
// Implementing the salary inside the SDE2 class
class SDE2 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary() { System.out.println(this.salary); }
}

public class GFG {

public static void main(String[] args)
{
SDE1 ob = new SDE1();
// Insert different salaries
ob.insertsalary(100000);
ob.printSalary();
SDE2 ob1 = new SDE2();

ob1.insertsalary(200000);
ob1.printSalary();
}
}

Output

100000
200000

Source: geeksforgeeks.org

Wednesday, July 14, 2021

Difference Between AOP and OOP

AOP vs OOP

AOP (Aspect-oriented programming) and OOP (Object-oriented programming) are two programming paradigms. A programming paradigm is a fundamental style of computer programming. Programming paradigms differ in how each element of the programs is represented and how each step is defined for solving problems. As the name suggests, OOP focuses on representing problems using real-world objects and their behavior, while AOP deals with breaking down the programs in to separate crosscutting concerns.

What is AOP?

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

AOP is a programming paradigm, which deals with breaking down a program in to cohesive areas of functionality (called concerns) that cut across multiple areas, in order to increase modularity. Support for abstractions (such as classes, methods, etc.) to group and encapsulate concerns in to unique entities is provided in many other programming paradigms. But concerns (such as “Logging”) are examples of crosscutting concerns, because every logged part of the system is affected by the strategy used for logging. The main focus of all AOP implementations is to have suitable crosscutting expressions to capture all concerns in a single location.

What is OOP?

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

In OOP, the focus is on thinking about the problem to be solved in terms of real-world elements, and representing the problem in terms of objects and their behavior. Classes depict the abstract representations of real world objects. Classes are like blueprints or templates, which gather similar items or things that can be grouped together. Classes have properties called attributes. Attributes are implemented as global and instance variables. Methods in the classes represent or define the behavior of these classes. Methods and attributes of classes are called the members of the class. An instance of a class is called an object. Therefore, an object is a data structure that closely resembles some real-world object.

There are several important OOP concepts such as Data abstraction, Encapsulation, Polymorphism, Messaging, Modularity and Inheritance. Typically, encapsulation is achieved by making the attributes private, while creating public methods that can be used to access those attributes. Inheritance allows the user to extend classes (called sub classes) from other classes (called super classes). Polymorphism allows the programmer to substitute an object of a class in place of an object of its super class. Typically, the nouns found in the problem definition directly become classes in the program. And similarly, verbs become methods. Some of the most popular OOP languages are Java and C#.

What is the difference between AOP and OOP?

The key difference between OOP and AOP is that the focus of OOP is to break down the programming task in to objects, which encapsulate data and methods, while the focus of AOP is to break down the program in to crosscutting concerns. In fact, AOP is not a competitor for OOP, because it emerged out of OOP paradigm. AOP extends OOP by addressing few of its problems. AOP introduces neat ways to implement crosscutting concerns (which might have been scattered over several places in the corresponding OOP implementation) in a single place. Therefore, AOP makes the program cleaner and more loosely coupled.

Wednesday, March 31, 2021

Difference Between Structured Programming and Object Oriented Programming

Structured Programming, Object Oriented Programming, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Guides

Structured Programming vs Object Oriented Programming

Object Oriented Programming (OOP) and Structured Programming are two programming paradigms. A programming paradigm is a fundamental style of computer programming. Programming paradigms differ in how each element of the programs is represented and how steps are defined for solving problems. As the name suggests, OOP focuses on representing problems using real-world objects and their behavior, while Structured Programming deals with organizing the program in a logical structure.

What is Structured Programming?

It is assumed that the birth year of Structured Programming is 1970. Structured programming is considered a subset of imperative programming. A structured program is made up of simple program flow structures, which are hierarchically organized. They are sequence, selection and repetition. Sequence is an order of statements. Selection means selecting a statement from a set of statements based on the current state of the program (for e.g. using if statements) and repetition means executing a statement until a certain state is reached (for e.g. using for or while statements). ALGOL, Pascal, Ada and PL/I are some of the structured programming languages used today.

What is Object Oriented Programming?

In OOP, the focus is on thinking about the problem to be solved in terms of real-world elements and representing the problem in terms of objects and their behavior. Classes depict the abstract representations of real world objects. Classes are like blueprints or templates, which gather similar items or things that can be grouped together. Classes have properties called attributes. Attributes are implemented as global and instance variables. Methods in the classes represent or define the behavior of these classes. Methods and attributes of classes are called the members of the class. An instance of a class is called an object. Therefore, an object is a data structure that closely resembles some real-world object.

There are several important OOP concepts such as Data abstraction, Encapsulation, Polymorphism, Messaging, Modularity and Inheritance. Typically, encapsulation is achieved by making the attributes private, while creating public methods that can be used to access those attributes. Inheritance allows the user to extend classes (called sub classes) from other classes (called super classes). Polymorphism allows the programmer to substitute an object of a class in place of an object of its super class. Typically, the nouns found in the problem definition directly become classes in the program. And similarly, verbs become methods. Some of the most popular OOP languages are Java and C#.

What is the difference between Structured Programming and Object Oriented Programming?

The key difference between Structured Programming and OOP is that the focus of Structured Programming is to structure the program in to a hierarchy of subprograms while, the focus of OOP is to break down the programming task in to objects, which encapsulate data and methods. OOP is considered more flexible than structured programming, because OOP separates a program in to a network of subsystems rather than structuring the program in to a hierarchy. Even though structuring provides certain clarity, a small change to a very large structured program may cause a ripple effect of having to change multiple subprograms.

Tuesday, January 12, 2021

Why Java is not a purely Object-Oriented Language?

Oracle Java Certification, Oracle Java Learning, Oracle Java Exam Prep, Oracle Java Career

Pure Object Oriented Language or Complete Object Oriented Language are Fully Object Oriented Language which supports or have features which treats everything inside program as objects. It doesn’t support primitive datatype(like int, char, float, bool, etc.). There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:

1. Encapsulation/Data Hiding

2. Inheritance

3. Polymorphism

4. Abstraction

5. All predefined types are objects

6. All user defined types are objects

7. All operations performed on objects must be only through methods exposed at the objects.

Example: Smalltalk

Why Java is not a Pure Object Oriented Language?

Java supports property 1, 2, 3, 4 and 6 but fails to support property 5 and 7 given above. Java language is not a Pure Object Oriented Language as it contain these properties:

◉ Primitive Data Type ex. int, long, bool, float, char, etc as Objects: Smalltalk is a “pure” object-oriented programming language unlike Java and C++ as there is no difference between values which are objects and values which are primitive types. In Smalltalk, primitive values such as integers, booleans and characters are also objects.

In Java, we have predefined types as non-objects (primitive types).

int a = 5; 

System.out.print(a);

◉ The static keyword: When we declares a class as static then it can be used without the use of an object in Java. If we are using static function or static variable then we can’t call that function or variable by using dot(.) or class object defying object oriented feature.

◉ Wrapper Class: Wrapper class provides the mechanism to convert primitive into object and object into primitive. In Java, you can use Integer, Float etc. instead of int, float etc. We can communicate with objects without calling their methods. ex. using arithmetic operators.

String s1 = "ABC" + "A" ;

Oracle Java Certification, Oracle Java Learning, Oracle Java Exam Prep, Oracle Java Career

Even using Wrapper classes does not make Java a pure OOP language, as internally it will use the operations like Unboxing and Autoboxing. So if you create instead of int Integer and do any mathematical operation on it, under the hoods Java is going to use primitive type int only.

public class BoxingExample 

{ 

public static void main(String[] args) 

{ 

Integer i = new Integer(10); 

Integer j = new Integer(20); 

Integer k = new Integer(i.intValue() + j.intValue()); 

System.out.println("Output: "+ k); 

} 

} 

In the above code, there are 2 problems where Java fails to work as pure OOP:

1. While creating Integer class you are using primitive type “int” i.e. numbers 10, 20.
2. While doing addition Java is using primitive type “int”.

Monday, July 20, 2020

How to change procedural code into object-oriented one?

What style should Clean Code be written in?


Clean Code is not always object-oriented. Sometimes it will be written in procedural style. And what style is better: procedural or object-oriented? We should perform the choice under given conditions which facilitates its development and readability – in accordance with the principles of Clean Code.

Below is an example of the procedural code that will help me consider the purity of the code and its refactoring to the object oriented code.

public class Rectangle {
    double width;
    double height;
}
...
public class Geometry {
    double area(Object shape) {
        if (shape instanceof Circle) {
            Circle circle = (Circle) shape;
            return Math.PI * circle.radius * circle.radius
        } else if (shape instanceof Rectangle) {
            Rectangle rectangle = (Rectangle) shape;
            return rectangle.width * rectangle.height;
        } else if (shape instanceof Square) {
            Square square = (Square) shape;
            return square.size * square.size;
        }

        throw new IllegalArgumentException("Unknown shape");
    }
}

I choose the style in which the code will be written on the basis of observing the direction of changes that result from emerging new business requirements.

What changes does the procedural code allow?


If I mainly add new functions operating on already existing data structures, then the procedural code (new procedures) will probably remain legible. An example is the new function that returns the smallest rectangle containing given figure.

public class Geometry {
    Rectange containingRectange(Object shape) {
        if (shape instanceof Circle) {
            Circle circle = (Circle) shape;
            Rectangle rectangle = new Rectangle();
            rectangle.width = 2 * circle.radius;
            rectangle.height= 2 * circle.radius;
            return rectangle;
        } else if (shape instanceof Rectangle) {
            return (Rectangle) shape;
        } else if (shape instanceof Square) {
            ...
        }

        throw new IllegalArgumentException("Unknown shape");
    }
}

When will the procedural code become illegible?


But if you plan to add or modify existing data structures, it will force changes to all existing procedures. What happens when I decide to change the components in the Rectangle data structure to points describing 2 opposite corners of the square?

public class Point {
    double x,y; 
} 
 
public class Rectangle {
     Point topLeft;
     Point bottomRight; 
}

It is not difficult to notice that such a change will force many changes to existing procedures. A way to avoid many changes (or minimize them) is to place the getX () and getY () methods in the Rectangle structure that will perform the necessary calculations.

public class Rectangle {
    private Point topLeft;
    private Point bottomRight;
 
    double getX(){
        return Math.abs(topLeft.x = bottomRight.x);
    }
 
    double getY(){
        return Math.abs(topLeft.y = bottomRight.y);
    }
}

But note that from that moment I start to hide details of the data structure. Details in the Rectangle class have been hidden and new methods calculate the necessary output. In this way, I am starting to change the code style from procedural to object oriented.

How to refactor a procedural code into an object-oriented one?


Perform self-encapsulation of data structures

At the beginning I add constructors and encapsulate details within data structures. In my case, the data in the structures are not changing, so the fields can be final.

public class Circle {
    private final double radius;
 
    public Circle(double radius) {
        this.radius = radius;
    }
 
    public double getRadius() {
        return radius;
    }
}

Define a common interface / base class for existing data structures

Next, I define an empty “Shape” base class that will expand all data structures. From now on, the “area” procedure accepts only the “Shape” abstract class extension as a parameter. Alternatively, it can also be a common interface.

public abstract class Shape{
}
 
public class Circle extends Shape {
    private final double radius;
 
    public Circle(double radius) {
        this.radius = radius;
    }
 
    public double getRadius() {
        return radius;
    }
}
 
...

Move the logic from the procedure to the base class

In order to transfer the logic to the base class, I will make a small modification to be able to use the method transfer in the IntelliJ tool.

public class Geometry {
    static double area(Shape shape) {
        return new Geometry().calculateArea(shape);
    }
 
    private double calculateArea(Shape shape) {
        if (shape instanceof Circle) {
            Circle circle = (Circle) shape;
            return Math.PI * circle.getRadius() * circle.getRadius();
        } else if (shape instanceof Rectangle) {
            Rectangle rectangle = (Rectangle) shape;
            return rectangle.getWidth() * rectangle.getHeight();
        } else if (shape instanceof Square) {
            Square square = (Square) shape;
            return square.getSize() * square.getSize();
        }
 
        throw new IllegalArgumentException("Unknown shape :" + shape.getClass());
    }
}

I obtained the above code by extracting a new method “calculateArea”, then deleting the word static and adding a call to the constructor.

Then I move the method containing the “calculateArea” logic from “Geometry” to the “Shape” base class.

public class Geometry {
    static double area(Shape shape) {
        return shape.calculateArea();
    }
}
 
public abstract class Shape {
    double calculateArea() {
        if (this instanceof Circle) {
            Circle circle = (Circle) this;
            return Math.PI * circle.getRadius() * circle.getRadius();
        } else if (this instanceof Rectangle) {
            Rectangle rectangle = (Rectangle) this;
            return rectangle.getWidth() * rectangle.getHeight();
        } else if (this instanceof Square) {
            Square square = (Square) this;
            return square.getSize() * square.getSize();
        }
 
        throw new IllegalArgumentException("Unknown shape :" + getClass());
    }
}

After this distortion, there was a code smell: “base class is dependent on its derived classes”. Solving the problem will lead us to the next transformation.

Push method down

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning

The transformation is fully automated in many environments like IntelliJ, Eclipse, NetBeans.

Delete unnecessary logic in derived classes


Finally, we finish with the transformation “replace conditional expressions with polymorphism”. In each of the subclasses (i.e. our old data structures), only one condition will be true.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning

The final result of our refactoring is below

public class Circle extends Shape {
    private final double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    @Override
    double calculateArea() {
        Circle circle = (Circle) this;
        return Math.PI * circle.getRadius() * circle.getRadius();
    }
}

public class Geometry {
    static double area(Shape shape) {
        return shape.calculateArea();
    }
}

In addition, we can inline “Geometry.area” function and then change the name of “calculateArea” to “area”, so we come back to old naming.

Interpreter pattern

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning

Monday, April 6, 2020

Class JavaDocs Should Be Mandatory in OOP

I’ll admit, the title is a bit of a lie. I actually believe JavaDocs are necessary everywhere: methods, attributes and classes. But let’s focus on classes for now. I should also mention that this idea applies to all object-oriented programming languages. I suppose there must be an equivalent to JavaDocs in most languages.

There are many different opinions about the importance of JavaDocs. Some find them rather useless, some use them only in libraries and some might have no idea what they are. I believe they are useful and should be mandatory in all object-oriented software. They are important in order for objects to be used correctly and they are also an indicator of the code’s quality.

Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Java Learning, Oracle Java Cert Exam
Tom & Jerry – The Two Mouseketeers, by William Hanna and Joseph Barbera

First of all, how should a class JavaDoc look? I suggest the following three points:

◉ explain what the class is;

◉ explain why/where it should be used;

◉ offer a small code snippet exemplifying its usage;

It should also mention at least the author and the @since annotation, indicating the version of the software with which the class has been introduced.

Here is an example:

/**
 * This is an abstract JsonObject you can extend if you want
 * to make your object Json-Polymorphic. Just give it the original
 * JsonObject body and you won't have to implement all of JsonObject's
 * methods anymore. E.g.
 * <pre>
 *  public final class CarFromJson
 *      extends AbstractJsonObject implements Car {
 * 
 *      public CarFromJson(final JsonObject car) {
 *          super(car);
 *      }
 *      //only methods of Car here
 *  }
 * </pre>
 * @author amihaiemil
 * @since 0.0.1
 */
abstract AbstractJsonObject implements JsonObject {

    private final JsonObject delegate;

    AbstractJsonObject(final JsonObject delegate) {
        this.delegate = delegate;
    }
    //...
}

How can it be an indicator of code quality? Well, I believe if you cannot write a JavaDoc like the one above; if it’s hard to find your words or clearly explain the purpose of a class in a few lines of text, then clearly the design is not ok: the scope of the class is too big, or it may do too many things, or it may be very hard to instantiate etc. Furthermore, if you cannot write a simple code example in <pre></pre> tags, that’s a read flag as well.

By the way, the <pre> tag is the HTML tag which preserves encapsulated text exactly as it is, it doesn’t change its indentation or anything. It’s perfect for snippets of code. More about it here.

Still, none of what I said above really makes them “mandatory”. There’s one more very good reason to have them: naming of the classes. Classes should be components with a clear purpose and usability guideline in mind. Therefore, the name may not be trivial. Take a look at the following class:

final class AssertRequest implements HttpClient {
    AssertRequest(
        final HttpResponse response,
        final Condition... conditions
    ) {
        this.response = response;
        this.conditions = Arrays.asList(conditions);
    }
    //...
}

Do you have any idea what it is? Or why is it named AssertRequest? Heck, it doesn’t even accept a Request as constructor parameter! My guess is: you’ve no idea what it is. So you try to open “Call Hierarchy” in your IDE to find where it is being used. But you find nothing, this is a class which has been written by another developer and it’s never been used so far. Of course, the developer also forgot to push the unit tests for it.

Here is the JavaDoc that should be on top of it:

/* 
 * Implementation of Apache's HttpClient which we can
 * use in our tests to intercept HTTP Requests, make assertions
 * on them and send back a mock HTTP Response.
 *
 * It is an alternative to having to use a real HttpClient and
 * starting an in-memory mock server.
 *
 * Use it like this:
 * <pre>
 *   @Test
 *   public void pingTrueIfResponseIsOk() throws Exception {
 *     MatcherAssert.assertThat(
 *       new LocalDocker(
 *         new AssertRequest(
 *           new Response(HttpStatus.SC_OK),
 *           new Condition(
 *             "HTTP Method should be GET!",
 *             req -> req.getRequestLine().getMethod().equals("GET")
 *           ),
 *         )
 *       ).ping(),
 *       Matchers.is(true)
 *     );
 *   }
 * </pre>
 * @author george
 * @since 0.0.1
 */

Now you know what it is and how to use it. Also, the name AssertRequest makes sense now: it was named like that in order to fit elegantly in test cases. Looking at the test above, it is clear that the mock HttpClient is actually making some assertions on the real HTTP Request that our Docker library is sending. Then, it returns the expected HTTP Response so we can see that our library is handling responses properly.

Again, this depends very much on naming conventions. My take on naming is that we should name classes for what they are, but we should also consider where they will be used and by whom. Depending on this, we might decide to choose a name that fits best in the context of usage and, as you saw above, the name might not make much sense by just looking at the class itself.

Wednesday, February 12, 2020

Difference between Class and Object in Java and OOPS with Example

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java OOPs, Oracle Java Prep

Class and Object are two most important concept of Object oriented programming language (OOPS)  e.g. Java. Main difference between a Class and an Object in Java is that class is a blueprint to create different objects of same type. This may looks simple to many of you but if you are beginner or just heard term Object Oriented Programming language it might not be that simple. I have met many students, beginners and programmers who don’t know difference between class and object and often used them interchangeably. Also Java API having classes like java.lang.Object and java.lang.Class also adds more confusion in beginners mind. Both of them are totally different things, class and object in OOPS are concepts and applicable to all Object oriented programming language e.g. C++ or Scala. On the other hand java.lang.Class and java.lang.Object are part of Java API. Along with other OOPS concepts like Abstraction, Encapsulation, Inheritance and Polymorphism, this is also one of the most fundamental of Object oriented programming (OOPS) which needs to be clearly understood before proceeding into serious application programming. Without clear understanding of Class and Object you are more prone to make errors, not able to comprehend an already written program and it would be pretty hard for you to find bugs or fix errors or exceptions in Java code.  In this article we will look this on different angles to differentiate Class and object in Java.

Difference between Class vs Object in OOPS and Java


Here is my list of differences between Class and Object in OOPS. Class and Object are related to each other because every Object must be type of any class. In the same time class itself is of no use until you create object. Let’s see these difference between class and object in points :

1) Class is blueprint means you can create different object based on one class which varies in there property. e.g. if Car is a class than Mercedes, BMW or Audi can be considered as object because they are essentially a car but have different size, shape, color and feature.

2) A Class can be analogous to structure in C programming language with only difference that structure doesn't contain any methods or functions, while class in Java contains both state and behavior, state is represented by field in class e.g. numberOfGears, whether car is automatic or manual, car is running or stopped etc. On the other hand behavior is controlled by functions, also known as methods in Java e.g. start() will change state of car from stopped to started or running and stop() will do opposite.

Oracle Class, Oracle Object in Java, Oracle OOPS, Oracle Java Tutorials and Material

3) Object is also called instance in Java and every instance has different values of instance variables. e.g. in following code

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Person p1 = new Person("Rakesh");
Person p2 = new Person("Jimmy");
Person p3 = new Person("Peter");

Here Person is a class as it defines design of Person objects i.e. How will a person object look like, what properties it will have etc. By the way Class is declared by keyword "class" in Java and p1, p2, p3 are different object of Person class. In natural language you can say different person which has different names where name is a property of Person Class. Another difference between Class and Object in Java is that we have a class keyword to declare class in Java but there is no object keyword. Objects are most notably created using new() operator, which calls constructor of class to create and initialize object in Java.

That’s all on difference between class and object in OOPS and Java. As I said main difference between class and object is that former is a design while later is actual thing. Class specifies how an object will look like and object belongs to a particular type. In Object oriented programming language you can find real examples of class and object in your surroundings e.g. Home can be a class and everyone’s home can be considered object of class home, because they are home but they are also different to other homes.

Wednesday, January 15, 2020

Java OOPs Concepts

In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts:

◉ Object
◉ Class
◉ Inheritance
◉ Polymorphism
◉ Abstraction
◉ Encapsulation

Apart from these concepts, there are some other terms which are used in Object-Oriented design:

◉ Coupling
◉ Cohesion
◉ Association
◉ Aggregation
◉ Composition

Oracle Java Study Materials, Oracle Java Learning, Oracle Java Prep, Java Online Exam

Object

Oracle Java Study Materials, Oracle Java Learning, Oracle Java Prep, Java Online Exam
Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.

Class

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

Oracle Java Study Materials, Oracle Java Learning, Oracle Java Prep, Java Online Exam
If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation

Oracle Java Study Materials, Oracle Java Learning, Oracle Java Prep, Java Online Exam
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

Coupling

Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation.

Cohesion

Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces.

Association

Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects:

- One to One
- One to Many
- Many to One, and
- Many to Many

Let's understand the relationship with real-time examples. For example, One country can have one prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have one prime minister (many to one), and many ministers can have many departments (many to many).

Association can be undirectional or bidirectional.

Aggregation

Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects.

Composition

The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically.

Advantage of OOPs over Procedure-oriented programming language


1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented programming language, it is not easy to manage if code grows as project size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global data can be accessed from anywhere.

Oracle Java Study Materials, Oracle Java Learning, Oracle Java Prep, Java Online Exam

Figure: Data Representation in Procedure-Oriented Programming

Oracle Java Study Materials, Oracle Java Learning, Oracle Java Prep, Java Online Exam
Figure: Data Representation in Object-Oriented Programming

3) OOPs provides the ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.