Yes.You can use any kind of method in an abstract class

public abstract class AbstractDAO{

public void save(){
  validate();
  //save
}
  private void validate(){ // we are hiding this method
  }
}

Private Constructors
If Private constructor is the only constructor of the class, then the reason is clear: to prevent subclassing. Some classes serve only as holders for static fields/methods and do not want to be either instantiated or subclassed. Note that the abstract modifier is in this case redundant—with or without it there would be no instantiation possible. The abstract modifier is also bad practice because it sends wrong signals to the class’s clients. The class should in fact have been final.

Abstract Class with Private Constructor is same as Final Class. Both serves the same purpose.

POJO Plain Old Java Object. Basically a class with attributes and its getters and setters.

public class User
{
 private String name;
 private int age;

 public void setName(String name){
    this.name = name;
 }

 public String getName(){
    return this.name;
 }

 //same for age

}

POJO vs Java Beans
A JavaBean is a Java object that satisfies certain programming conventions:

  1. all JavaBean properties must have public setter and getter methods (as appropriate);
  2. all JavaBean instance variables should be private.
  3. the JavaBean class must have a no-arg constructor
  4. the JavaBean class must implement either Serializable or Externalizable;

Advantages of Bean

  1. A Bean obtains all the benefits of Java’s “write-once, run-anywhere” paradigm.
  2. The properties, events, and methods of a Bean that are exposed to an application
    builder tool can be controlled.
  3. A Bean may be designed to operate correctly in different locales, which makes it
    useful in global markets.
  4. The configuration settings of a Bean can be saved in persistent storage and restored
    at a later time.
  5. A Bean may register to receive events from other objects and can generate events that
    are sent to other objects.

Advantages of POJO

  1. Getter & setter methods allow you to change the underlying data type without breaking the public interface of your class which makes it (and your application) more robust and resilient to changes
  2. You might want to call some other code such as raising a notification when the value is obtained or changed like in java bean. This is not possible with your current class.
  3. You can expose values that are not backed by a field I.E. calculated values such as getFullName() which is a concatenation of getFirstName() and getLastName() which are backed by fields.
  4. You can add validation to your setter methods to ensure that the values being passed are correct. This ensures that your class is always in a valid state.
  5. If the field is an object (I.E. not a primitive type) then the internal state of your class can be modified by other objects which can lead to bugs or security risks. You can protect against this scenario in your POJO’s getter by returning a copy of the object so that clients can work with the data without affecting the state of your object. Note that having a final field does not always protect you against this sort of attack as clients can still make changes to the object being referenced (providing that object is itself mutable) you just cannot point the field at a different reference once it has been set.

Spring vs EJB

App servers written to support the EJB standard can, in theory, be ported from one compliant Java EE app server to another. But that means staying away from any and all vendor-specific extensions that lock you in to one vendor.

Spring ports easily between app servers (e.g., WebLogic, Tomcat, JBOSS, etc.) because it doesn’t depend on them

Spring Boot offers an even better way to write applications without Java EE app servers. You can create an executable JAR and run it on a JVM.

The Spring framework sits on top of the application servers and service libraries. Service integration code (e.g. data access templates) resides in the framework and is exposed to the application developers. In contrast, the EJB 3 framework is integrated into the application server and the service integration code is encapsulated behind an interface. EJB 3 vendors can thus optimize the performance and developer experience by working at the application server level. For example, they can tie the JPA engine closely to JTA transaction management. Another example is clustering support which is transparent to EJB 3 developers

Spring vs J2EE

Strictly speaking, Spring is a framework while Java EE is a specification which is implemented by various softwares such as JBoss and Glassfish.
The greatest difference is that Spring is an actual library while JavaEE is an API that has to be implemented. Depending on the JAVA EE container you could find a full implementation (e.g. Glassfish), a partial implementation (e.g. Tomcat) a full implementation with extra sugar (e.g. JBoss and others).

Is it possible to create Object for abstract class?

abstract class my {
    public void mymethod() {
        System.out.print("Abstract");
    }
}

class poly {
    public static void main(String a[]) {
        my m = new my() {};
        m.mymethod();
        System.out.println(m.getClass().getSuperclass());
    }
}

No, we can’t.The abstract super class is not instantiated by us but by java.

In the above code we are creating object for anonymous class.

my m = new my() {};

When the above code is compiled will result in following class file creation

My.class
Poly$1.class  // Class file corresponding to anonymous subclass
Poly.class

anonymous inner type allows you to create a no-name subclass of the abstract class

When the above code is run the output would be

Output

 Abstract
 class my

Now lets override the method in anonymous inner class like one below.

abstract class my {
    public void mymethod() {
        System.out.print("Abstract");
    }
}

class poly {
    public static void main(String a[]) {
        my m = new my() {
          public void mymethod() {
               System.out.print("Overridden in anonymous class");
           }
        };
        m.mymethod();
        System.out.println(m.getClass().getSuperclass());
    }
}

Output

 Overridden in anonymous class
 class my

Anonymous inner class with same name as abstract class are child classes of abstract class.

There may be times where one may think that I can extend parent class instead of implementing interface. Lets see whats When to choose inheritance over an interface and interface over inheritance.

inheritance over an interface
The main drawback of interfaces is that they are much less flexible than classes when it comes to allowing for the evolution of APIs. Once you ship an interface, the set of its members is fixed forever. Any additions to the interface would break existing types implementing the interface.

A class offers much more flexibility. You can add members to classes that you have already shipped. As long as the method is not abstract (i.e., as long as you provide a default implementation of the method), any existing derived classes continue to function unchanged.

interface over inheritance
Lets take the following code

Mammal.java

public abstract class Animal
{
 public void abstract mate();
 public void abstract feed();
}

Now the above abstract class has two methods mate() and feed().

public class Dog extends Animal
{
}

public class Cat extends Animal
{
}

Now we have Dog and Cat concrete classes extending Animal.

we have few more classes extending Animal

public class Giraffe extends  Animal{}
public class Rhinoceros extends  Animal{}
public class Hippopotamus extends  Animal{}

Now the classes Dog and Cat are pet animals. So it should implement pet behavior. This can be done in two ways.

  1. By defining isPet() method in base class and overriding in child class
  2. By implementing pettable interface.

Now implementing interface is easy compared to overriding method defined in base class because

  1. Interface favours clean code. Defining and Overriding the class may increase code redundancy
  2. Now you get a parakeets which is again a pet and could also fly.If you are inheriting the base class then you need to add canFly() method in base class and set it to return false and override in the parakeets class to return true.

    public class  parakeets extends Animal
    {
      .
      .
        public boolean canFly()
        {
            return true;
        }
    }
    

    Instead you can declare a interface flyable and implement the interface method without making changes to base class

    public class  parakeets extends Animal implements flyable 
    {
      .
      .
        public boolean canFly()
        {
            return true;
        }
    }
    
  3. Interface may be completely not related to class in which it is implemented. Say lets define a carpenter ants class which always moves one after another.Now this can be represented to implement queuing interface which has nothing to do with other animals other then carpenter ants since only ants of this type follows a queue system when they migrate from one place to another

Scenario 1:
If you have a clear analysis and Design in UML then you can start with the interface.

Scenario 2:
The interface shows up when you need to refactor common features out of several classes.Until you have multiple classes with common features, it’s hard to foresee what the interface should be.

Write a class and extract interface later. Usually the reason for extracting an interface is the need for a second implementation of that interface (often as a mock for unit testing)

Maven acts as both a dependency management tool – it can be used to retrieve jars from a central repository or from a repository you set up – and as a declarative build tool. The difference between a “declarative” build tool and a more traditional one like ant or make is you configure what needs to get done, not how it gets done. For example, you can say in a maven script that a project should be packaged as a WAR file, and maven knows how to handle that.

Maven relies on conventions about how project directories are laid out in order to achieve its “declarativeness.” For example, it has a convention for where to put your main code, where to put your web.xml, your unit tests, and so on, but also gives the ability to change them if you need to.

Comparable is for objects with a natural ordering. The object itself knows how it is to be ordered.If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.

Comparator is for objects without a natural ordering or when you wish to use a different ordering.

Natural ordering is the Ordering implemented on the objects of each class. This ordering is referred to as the class’s natural ordering.For example Strings Natural Ordering is defined in String Class

Comparable
Compares object of itself with some other objects.Comparable overrides compareTo

Employee.java

package com.acme.users;

public class Employee implements Comparable<Employee> {
	public String EmpName;
	public Integer EmpId;
	public Integer Age;
	
	public Employee(Integer pEmpId, String pEmpName, Integer pAge)
	{
		this.EmpName = pEmpName;
		this.EmpId   = pEmpId;
		this.Age     = pAge;
	}
	
	
	public String getEmpName() {
		return EmpName;
	}
	public void setEmpName(String empName) {
		EmpName = empName;
	}
	public Integer getEmpId() {
		return EmpId;
	}
	public void setEmpId(Integer empId) {
		EmpId = empId;
	}
	public Integer getAge() {
		return Age;
	}
	public void setAge(Integer age) {
		Age = age;
	}
	
	@Override
	public int compareTo(Employee arg0) 
	{	
		if(this.getEmpId() == arg0.getEmpId())
			return 0;
		else if (this.getEmpId() > arg0.getEmpId())
			return 1;
		else
			return -1;
	}
}

EmpDashBoard.java

package com.acme.users;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EmpDashBoard {
	public static void main(String[] args) {

		List<Employee> arrEmpList = new ArrayList();

		Employee objEmp1 = new Employee(101, "Ahmed", 31);
		Employee objEmp2 = new Employee(127, "Mahesh", 24);
		Employee objEmp3 = new Employee(109, "Viparna", 85);
		Employee objEmp4 = new Employee(101, "Abdul", 26);
		Employee objEmp5 = new Employee(104, "Muthu", 23);
		Employee objEmp6 = new Employee(115, "Monalisa", 25);

		arrEmpList.add(objEmp1);

		arrEmpList.add(objEmp2);
		arrEmpList.add(objEmp3);
		arrEmpList.add(objEmp4);
		arrEmpList.add(objEmp5);
		arrEmpList.add(objEmp6);

		System.out.println("Sorted based on Natural Sorting(Emp Id)");
		System.out.println("Before Sorting");
		dispListContent(arrEmpList);
		
		Collections.sort(arrEmpList);
		
		System.out.println("After Sorting");
		dispListContent(arrEmpList);
	}

	public static void dispListContent(List<Employee> parrEmployeeLst) {
		System.out.println(" ");

		System.out.println("EmpId" + " " + "EmpName" + "     " + "Age");
		System.out.println("---------------------------");
		for (Employee object : parrEmployeeLst) {
			System.out.print(object.getEmpId() + "   ");
			System.out.print(object.getEmpName() + "     ");
			System.out.println(object.getAge() + " ");
		}
	}
}

Output

Sorted based on Natural Sorting(Emp Id)

Before Sorting
 
EmpId EmpName     Age
---------------------------
101   Ahmed       31 
127   Mahesh      24 
109   Viparna     85 
101   Abdul       26 
104   Muthu       23 
115   Monalisa    25 

After Sorting
 
EmpId EmpName     Age
---------------------------
101   Ahmed       31 
101   Abdul       26 
104   Muthu       23 
109   Viparna     85 
115   Monalisa    25 
127   Mahesh      24 

Comparator
In some situations, you may not want to change a class and make it comparable. In such cases, Comparator can be used.Comparator overrides compare

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

In the below Example I have Sorted the Employee class Objects based on Name(EmpNameComparator), Age(EmpAgeComparator) and based on EmpIDName(EmpIdNameComparator)

EmpDashBoard.java

package com.acme.users;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EmpDashBoard {
	public static void main(String[] args) {

		List<Employee> arrEmpList = new ArrayList();

		Employee objEmp1 = new Employee(101, "Ahmed", 31);
		Employee objEmp2 = new Employee(127, "Mahesh", 24);
		Employee objEmp3 = new Employee(109, "Viparna", 85);
		Employee objEmp4 = new Employee(101, "Abdul", 26);
		Employee objEmp5 = new Employee(104, "Muthu", 23);
		Employee objEmp6 = new Employee(115, "Monalisa", 25);

		arrEmpList.add(objEmp1);

		arrEmpList.add(objEmp2);
		arrEmpList.add(objEmp3);
		arrEmpList.add(objEmp4);
		arrEmpList.add(objEmp5);
		arrEmpList.add(objEmp6);

		System.out.println("Sorted based on Natural Sorting(Emp Id)");

		System.out.println("Before Sorting");
		dispListContent(arrEmpList);

		System.out.println("Sorting based on Emp Name");
		Collections.sort(arrEmpList, new EmpNameComparator());
		dispListContent(arrEmpList);

		System.out.println("Sorting based on Emp Age");
		Collections.sort(arrEmpList, new EmpAgeComparator());
		dispListContent(arrEmpList);

		System.out.println("Sorting based on EmpId and Name");
		Collections.sort(arrEmpList, new EmpIdNameComparator());
		dispListContent(arrEmpList);
	}

	public static void dispListContent(List<Employee> parrEmployeeLst) {
		System.out.println(" ");

		System.out.println("EmpId" + " " + "EmpName" + "     " + "Age");
		System.out.println("---------------------------");
		for (Employee object : parrEmployeeLst) {
			System.out.print(object.getEmpId() + "   ");
			System.out.print(object.getEmpName() + "     ");
			System.out.println(object.getAge() + " ");
		}
	}
}

EmpNameComparator.java

public class EmpNameComparator implements Comparator<Employee>{

	@Override
	public int compare(Employee o1, Employee o2) {
		String a = o1.getEmpName();
		String b = o2.getEmpName();
		
		//Strings Natural Order Comparable Method
		int compare = a.compareTo(b);
		
		if (compare > 0){
		    return 1;
		}
		else if (compare < 0) {
			return -1;
		}
		else {
			return 0;
		}
	}
}

EmpAgeComparator.java

public class EmpAgeComparator  implements Comparator<Employee> {
	
	@Override
	public int compare(Employee o1, Employee o2) {
		Integer a = o1.getAge();
		Integer b = o2.getAge();
		
		if (a > b){
		    return 1;
		}
		else if (a < b) {
			return -1;
		}
		else {
			return 0;
		}
	}
}

EmpIdNameComparator.java

public class EmpIdNameComparator  implements Comparator<Employee>{
	
	@Override
	public int compare(Employee o1, Employee o2) {
		String a = o1.getEmpName();
		String b = o2.getEmpName();
		
		
		int i = Integer.compare(o1.getEmpId(), o2.getEmpId());
		if (i != 0) return i;

	    return a.compareTo(b);
	}
	
}

Output

Before Sorting
 
EmpId EmpName     Age
---------------------------
101   Ahmed      31 
127   Mahesh     24 
109   Viparna    85 
101   Abdul      26 
104   Muthu      23 
115   Monalisa   25 

Sorting based on Emp Name
 
EmpId EmpName     Age
---------------------------
101   Abdul      26 
101   Ahmed      31 
127   Mahesh     24 
115   Monalisa   25 
104   Muthu      23 
109   Viparna    85 

Sorting based on Emp Age
 
EmpId EmpName     Age
---------------------------
104   Muthu       23 
127   Mahesh      24 
115   Monalisa    25 
101   Abdul       26 
101   Ahmed       31 
109   Viparna     85 

Sorting based on EmpId and Name
 
EmpId EmpName     Age
---------------------------
101   Abdul       26 
101   Ahmed       31 
104   Muthu       23 
109   Viparna     85 
115   Monalisa    25 
127   Mahesh      24 


comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

If there is a natural or default way of sorting Object already exist during development of Class than use Comparable. This is intuitive and you given the class name people should be able to guess it correctly like Strings are sorted chronically, Employee can be sorted by there Id etc. On the other hand if an Object can be sorted on multiple ways and client is specifying on which parameter sorting should take place than use Comparator interface. for example Employee can again be sorted on name, salary or department and clients needs an API to do that. Comparator implementation can sort out this problem.

Spring MVC uses 2 design Patterns Internally

  1. Front Controller
  2. MVC

How Spring MVC Handles Request

  1. Receive the request from client
  2. Consult Handle Mapper to decide which controller processes the request
  3. Dispatch the request to the controller
  4. Controller processes the request and returns the logical view name and model back to DispatcherServlet
  5. Consult View Resolver for appropriate View for the logical view name from Controller
  6. Pass the model to View implementation for rendering
  7. View renders the model and returns the result to DispatcherServlet
  8. Return the rendered result from view to the client

MappingHandler
DispatcherServlet uses MappingHandler to find out which controller is right one for this request.There are many MappingHandler implementations which uses different strategies to map the request to Controller. By default DispatcherServlet will use BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping.

public interface HandlerMapping 
{
      HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}

ViewResolver
With the help of ViewResolver strategy object DispatcherServlet can find out physical view from the logical view name. Similar to MappingHandler there are also many different strategies for resolving the view based on the different view technologies. Most commonly used implementation of ViewResolver is InternalResourceViewResolver.

public interface ViewResolver 
{
      View resolveViewName(String viewName, Locale locale) throws Exception;
}

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.Inversion of Control (IoC) means any sort of programming style where an overall framework or run-time controlled the program flow.

Dependency Injection is a Type of IoC

IoC means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside service (for example, xml file or single app service).

DI means the IoC principle of getting dependent object is done without using concrete objects but abstractions (interfaces). This makes all components chain testable, cause higher level component doesn’t depend on lower level component, only from interface.

Techniques to implement inversion of control

  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection of any given below type:
    1. a constructor injection
    2. a setter injection
    3. an interface injection

DI is a form of IoC, where implementations are passed into an object through constructors/setters/service look-ups, which the object will ‘depend’ on in order to behave correctly.

IoC without using DI, for example would be the Template pattern because the implementation can only be changed through sub-classing.

DI Frameworks are designed to make use of DI and can define interfaces (or Annotations in Java) to make it easy to pass in implementations.