Why Multiple Inheritance in Java not supported?

Multiple Inheritance in Java is not supported

For making Java language simple and avoid complexities present in earlier languages like c++, the founder of java(James Gosling) decided that java shouldn’t support Multiple Inheritance.

In a white paper titled “Java: an Overview” James Gosling gives an idea on why multiple inheritance is not supported in Java.

Gosling on omission of Multiple Inheritance in Java

“JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions.”

Ambugity problem due to Multiple Inheritance

If we try to do multiple inheritance in java we will come across an ambiguity problem. We will discuss about it below using an example.

Multiple Inheritance in Java is Not Supported

We have a super class A having a function called fun().
Two subclasses B and C extend class A providing their own implementation of fun() function.

Assume class D inherits from class B and class C.
If we create an object of class D and try to access function fun() guess what will happen.
i.e D obj=new D(); obj.fun();

This will lead to ambiguity problem. Because it’s difficult for java to decide which version of fun() function to execute, fun() of class B or fun() of class C. The above problem is also referred as diamond problem.

In c++ we have multiple inheritance and the problem is resolved using scope resolution operator. But java founders wanted to keep java simple and avoid complexities. Concepts like pointers, operator overloading are also avoided in java language for the same reason.

Multiple Inheritance in Java is not much required

Extending from two different classes having different implementations of a function is not much required in real world.

Ejb1 vs Ejb2 vs Ejb3 | JavaTutorOnline

Ejb1 vs Ejb2 vs Ejb3

Ejb1 had limited functionality just as a lady bug that doesn’t do much work still is appreciated by people due to its beauty.

Ejb2 was very heavy like the Elephant with functionalities. Still to take proper use of the elephant power it had to be tamed, or Ejb2 was later simplified to Ejb3

Ejb3 is very simple having power and is serving the people very well like a cow giving milk to the universe.

Overview of EJB

Ejb is a platform for building ,reusable, portable and scalable business applications using java.

Ejb helps developers to concentrate on building business logic code without having to build infrastructure code comprising of functionalities including transactions, security, automated persistence that are provided by the Ejb container.

Ejb as Component

Ejbs are server side components that you can use to build parts of an application like business logic or persistence code. These components in Ejb3 are simple POJO with special power. Component means that the user need not know the inner working of the Component, he only needs to know what he has to give and what the Component will give you i.e. application behavior has to be completely encapsulated from the outside world.

There are 3 types of Ejbs. Session beans taking care of business logic. Entity Bean used for persistence. Message driven beans.

One of the most important use of Ejbs is its reusability. E.g. If there is a site for online books that is using an Ejb code for checking credit card. Then if we create another Website for CDs then we can reuse the same credit card Ejb. The first Ejb can be put as an Ejb component or a web service that is used by both applications.

uses Credit card Ejb

Ejb as Framework

The Ejb Container houses the Ejb components we develop. This Ejb Container together with the Ejb Component act as a Framework with predefined functionalities. This relieves the programmer from coding certain areas like transaction, security and persistence that are provide by the Ejb Container itself. Like if a programmer is creating a bean related to processing a credit card he need not create coding for the Transaction and Security that is provided by the Ejb Container Automatically.

We can use metadata annotations in our beans to specify what all services and functionalities we require. These are added dynamically when required during deployment. Metadata annotations is a way to specify the properties in a POJO, and these functionalities get automatically added. So we can say a POJO + Metadata annotation=Ejb3 bean. So we don’t need any outside xml configuration files.

Ejb is a specification which is followed by a large group of user vendors creating application server. So all have to follow the same specification making our applications portable.

Domain Driven Design

DDD is the preferred way as compared to the traditional four tired architecture followed by Ejb 2.

Following DDD the domain objects should contain buisness logic and shouldn’t be just a replica of database record. Incase of Ejb 2 beans were not POJOS and didn’t support OO features like inheritance, polymorphism.

Ejb3 helps follow DDD. Beans created using Ejb3 JPA supports polymorphism, inheritance etc.

Why choose EJB 3 among other technologies

Ease of use, Integrated solution stack— Ejb3 offers a complete stack of server solutions, including persistence, dependency injection, interceptors i.e. we won’t need to look for third party solutions to integrate in our application.

Ant Java Build Tool Tutorial | JavaTutorOnline

Ant Java Build Tool

Ant is a Java build tool. It is an open source program designed to help develop, and build big programs by automating the work tasks of compiling code, running tests, and Packaging the results for redistribution.

It is written completely in Java there by it is platform independent, easy to use, extensible, and scalable. It can be used in a small personal project, or it can be used in a large, project. It automates the entire build process.

In Ant build files are used to describe how to build a project. In the build file

developers list the high-level goals called the targets and actions to take to achieve each goal called the tasks. Each project contains multiple targets. Targets can depend on other targets. Targets contain tasks and Tasks do the work

Working with ANT

First ANT has to be downloaded and installed in the developers machine. Then the Path of the computer should be set to point to the bin directory of ANT. An environment variable called ANT_HOME should also be made in the System variables pointing to the installation directory of ANT.

A build.xml file should be created that will contain several targets that will further contain different tasks.

1) Target containing Tasks for creating build/classes directory to contain compiled files and creating a dist folder to contain the jar or war file of the project.

2) A Target to compile the java files in the source folder and put it into the build/classes folder.

3) A Target that will package the project to a jar or war file.

4) A Target to create the java docs of the project.

5) A Target to run all the tests on the project.

6) A Target to run the class file containing the main method.

After following the steps the user can simply type ant on the command line and ANT will read the “build.xml” and execute all the targets.

Some of the very important benefits of ANT are as follows:

Ant is free and Open Source. Ant makes it easy to bring developers into a project. It is widely supported. It integrates testing into the build processes and enables continuous integration. It runs inside Integrated Development Environments

Java Exception Handling Tutorial| How to Handle Exceptions in Java

What are Exceptions in Java?

An Exception in java is an object  that describes an exceptional condition in the program. A java exception object may be either generated in the code manually or automatically by the java run time system.

Java Exception Hierarchy

All types of java exceptions are subclass of the inbuilt class Throwable.  The two sub classes of Throwable are Exception and Error. The branch Exception deals with those exceptional conditions that the user program should handle. Exception further branches into RunTimeException and Checked Exceptions. RuntimeExceptions are those exceptions that are automatically defined for the programs that we write, like ArithmeticException, NullPointerException etc. The other branch is Error, which defines exceptions that are not expected to be handled by our program.

Java Exception Handling Hierarchy

A java program passes through compile time and run time. Exceptions are run time errors.

Exception is an inbuilt class in the java.lang package. There are many sub classes of Exception class like ArithmeticException, NullpointerException etc.

Depending upon the nature of the problem occurring during run time, java creates the appropriate Exception object and throws it.

For example:   int i = 1/0;  [Java will throw ArithmeticException type of object]

Why do we need to do Java Exception handling?

Java’s Default exception handlers  doesn’t do the work properly, they stop the program execution abruptly and gives  a weird output to the user. This is the reason why we should do exception handling. To do java exception handling  we have to use try and catch blocks. The lines of code that may throw some exception should be put in the try block and whatever we want to be done should be put in to the catch block.

Here, by doing 1/0, our program will stop abruptly. And it will give a weird error message. Like,

Exception in thread “main” java.lang.ArithmeticException: / by zero
at Exception_Demo.main(Exception_Demo.java:6)

But on using try and catch the problem is overcome.

Try Catch Block in Java Exception Handling

  • Try Block– Those code that may lead to exceptions during run time are generally put inside the try block.
  • Catch Block– What ever we want to do when ever any exception occurs should be put in the catch block.

Due to the use of try catch block the above program will not stop abruptly, rather it will give a customized exception message during run time.

Multiple catch blocks

There are many sub classes of the class Exception like ArithmeticException, NullPointerException etc. During run time different type of exception may occur depending on different conditions. So to handle the problems differently in different circumstances we need to have multiple catch blocks.

In this example, if length is 0 than it will be caught by catch block handling ArithmeticException. If we go out of the range of the array an ArryIndexOutOfBoundException is thrown. Programs may have various type of exceptions which can be handled through multiple catch blocks. In this example third catch block is for general Exception type. The general Exception catch block should be put at the end.

How to Create Custom Exception Class?

There are some situations that is not an exception for java but it is an exception for our project. For example if you want to run your program only when user gives commandline input (this is your program need which is not an exception for java) so, this is the time when we manually create our own exception class. To create a custom exception we have to extent the inbuilt Exception class.

Throw Keyword

Throw keyword is used for manually throwing java exception objects.

When a custom exception object is thrown it has to be handled through try and catch blocks because it cannot be handled by the default exception handler of java.

Throws Keyword

When we define a function and we don’t want to put try and catch block than we can use throws keyword. The caller of the function has to put the try and catch blocks. Throws keyword is for delegating the exception handling mechanism to the caller of the function.


Checked and unchecked exception

Unchecked exceptions are those exceptions that can be handling by java’s default exception handlers. If we try to throw unchecked exception inside a function we don’t need to put try and catch block nor the throws.

Checked exceptions are those exceptions that can’t handle by java’s default exception handlers.
When a checked exception is thrown from inside a function we are bound to put the try and catch block or the throws declaration.

List of checked exceptions

ClassNotFoundExceptionClass not found
CloneNotSupportedExceptionAttempt to clone an object that does not implement the Cloneable interface
IllegalAccessExceptionAccess to a class is denied
InstantiationExceptionAttempt to create an object of an abstract class or interface
InterruptedExceptionOne thread has been interrupted by another thread
NoSuchFieldExceptionA requested field does not exist
NoSuchMethodExceptionA requested method does not exist

List of unchecked exceptions

ArithmeticExceptionArithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds
ArrayStoreExceptionAssignment to an array element of an incompatible type
ClassCastExceptionInvalid cast
IllegalArgumentExceptionIllegal argument used to invoke a method
IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread
IllegalStateExceptionEnvironment or application is in incorrect state
IllegalThreadStateExceptionRequested operation not compatible with current thread state
IndexOutOfBoundsExceptionSome type of index is out-of-bounds
NegativeArraySizeExceptionArray created with a negative size
NullPointerExceptionInvalid use of a null reference
NumberFormatExceptionInvalid conversion of a string to a numeric format
SecurityExceptionAttempt to violate security
StringIndexOutOfBoundsAttempt to index outside the bounds of a string
UnsupportedOperationExceptionAn unsupported operation was encountered