Difference between final, finally and finalize

 

Every java interview might have this question asked for a beginner. Probably this is the most known question and well sort for answers. Though there are tons of other articles explaining the differences about these, I am planning to put those difference in a slightly different and more understandable. I am expecting that I will definitely reach my objective, while it’s the perception of the reader that is really important.

Continue reading →

Posted in JAVA | Leave a comment

Abstraction and Encapsulation Demystified

Abstraction in OOPS is well articulated, and states clearly of hiding the unnecessary details from other Components. Abstraction and Encapsulation comes hand in hand and often lead to misconceptions. In this article I would love to clear out all the ambiguity you ever had in mind about Abstraction and Encapsulation and their implementation in Java.

Wikipedia Definitions:

“In computer science, abstraction is the process of separating ideas from specific instances of those ideas at work. Computational structures are defined by their meanings (semantics), while hiding away the details of how they work.”

“Encapsulation is the packing of data and functions into a single component. The features of encapsulation are supported using classes in most object-oriented programming languages, although other alternatives also exist. It allows selective hiding of properties and methods in an object by building an impenetrable wall to protect the code from accidental corruption.”

In layman terms, abstraction means hiding, and encapsulation means packing / gluing things together.

Continue reading →

Posted in JAVA, OOPS | Tagged | Leave a comment

Factories in Software Development

From our childhood, we hear a lot of things about “Factories”, some are good and most of them are bad. That too if you are coming from a country like India, you will hear more bad stories of the factories destroying the communities and health.

In my own experience, I have heard a lot of criticism on factories, like they spoil the environment, contaminate the water, air and soil and devastation of the crops. When compared to the opportunities these give to the jobless the devastation gains and protests start.

Luckily, in Software development the “Factories” are doing the quite opposite of the physical “Factories” around the globe. As I have said above the “Factories” we are talking about reduces the pollution, improves the quality and gives more opportunities. (Ok finally one thing in common).

Continue reading →

Posted in Uncategorized | Tagged , | Leave a comment

Sorting Binary Array with O(n) complexity

Welcome back, today am going to discuss about a solution I came up when solving a sorting problem given by my colleague. The problem statement is very simple and straight “Sort an Array of Binary Digits, with O ( n ) complexity (without using extra memory)”. 

Continue reading →

Posted in Uncategorized | Leave a comment

Novice Info: Uninstalling Software From Eclipse

 

Today, I am planning to present a small tip, which I wanted to share from a long time. Many of us use Eclipse for all our development needs. The main reason being, it is well organized and has the wonderful framework for adding any capabilities for building on more features to it. In my opinion the awesome feature of writing and adding Plugins and Features of the eclipse for its extended support is the main reason for its penetration into the developer market.

Installation of plugins is very simple and easy in eclipse, inherently like maven it does have a repository for all the plugins and features call the update site, and from there you should be able to install any new feature/capability to the eclipse is very easy. There are of course a number of ways, to install these new features in eclipse, and these are out of scope for the content in this blog. The same way we have many ways to uninstall the software in eclipse, and in this blog am going to present what I know and applied in the my development experience.

First of all, before going any step forward about the ways of uninstalling a software, let us try to understand the reasons of why we need to think about removing any capability from eclipse.

  • If your eclipse is having many capabilities, and you are not using most of them in day 2 day development
  • Unused software in the background is hitting the performance of the eclipse
  • Need of installing new feature, which will not be compatible with the existing features.

These were some of the reasons, for uninstalling software from eclipse. Now, without taking any more time of yours let us look about the ways of uninstalling a feature on the eclipse.

Using Install Software Option:

  • Open “Install New Software” dialog box, by navigating through Help –> Install New Software.

image

  • Click on the “already Installed?” link as show in the above picture.

image

  • Select the features to be removed, and select Uninstall button.
  • Once the features are uninstalled your Eclipse program will be restarted, for the next use.

Voila, you are done with the Uninstallation of the features in eclipse.

Note: Yes you can definitely remove software, by deleting the jars in plugins and features directory in “ECLIPSE_HOME/” folder. But I don’t advice this as, it might break some other dependent plugins. Do this at your own risk of corrupting the Development Environment.

Thanks for the patience, in reading the article, and hope this was useful and not a waste of your precious time. Do comment your opinions and suggestions on making these articles a value for the next readers.

Posted in Uncategorized | Leave a comment

Importance of Data Structures and Algorithms in Programming

 

Today, I had a discussion with my colleague (Raveendra Chikkala), about Data Structures. It was a really interesting and motivating discussion, and today I wanted to share it with all of you. I have never taken the complexities of the algorithms seriously till date in my day to day programming, though I cared a lot on the design patterns and worked hard on making the system loosely coupled and having high cohesion.

Gist of the discussion is as follows:

Me: Why do we need to think of Data Structures, what do you mean by Data Structures. I know we use the data structures to store the data, and faster retrieval.

Friend: Yes, Data Modeling and Retrieving, is all about data structures, but we need to consider the complexity of the programs we write in every day programming, if we just use the data structures, and not considering the complexity of your own code is wrong. Predefined Data Structures, follows a set of algorithms, so that the data retrieval and update functions will be of high performance. While, it is also our responsibility to have good performance of the code we write.

Below is the example, he gave to justify his statement.

For Example Consider two lists List1 having some elements and L2 is having some elements. Now try to find the intersection of these two lists.

My Solution:

   1: for(Object ob: list1){

   2:     if(list2.contains(ob)){

   3:         list3.add(ob);

   4:     }

   5: }

He calculated the complexity of my logic as Looping n times in List1 will have a complexity of “N”, and complexity of contains() method on List2 is “N”, then the complexity of the logic above becomes N*N = N2 , which means the complexity increases exponentially. Consider each List is having 1 Million objects then the complexity will become 1000 Billion calculations.

His Solution:

   1: Collections.sort(list1);

   2: Collections.sort(list2);

   3: if(list1.size() > list2.size){

   4:     for(Object ob:list1){

   5:         if(Collections.binarySearch(list2,ob)>=0){

   6:             list3.add(ob);

   7:         }

   8:     }

   9: } else {

  10:  for(Object ob:list2){

  11:        if(Collections.binarySearch(list1,ob)>=0){

  12:            list3.add(ob);

  13:        }

  14:    }

  15: }

The above algorithm will have the complexity as follows, as Collections.sort() uses merge sort technique, and its complexity is given as “nlogn” since we are calling Collections.sort() method twice on 2 lists the complexity will be “2*nlogn” . The looping will have the complexity of “n” and as the binary search is having the complexity of “log(n)”. Hence the complexity of the loop becomes “n*logn”. So the total complexity of the system will be “2*nlogn +n*logn”. Which is a Linear complexity. Considering each List is having 1 Million objects then the complexity will become “(2*106*2.5)+(106*2.5) = 7.5” Million calculations.

So, his solution of getting an intersection of two lists is far far far…. better than my way. I was shocked to see this, and understood the importance of understanding the complexity of the algorithms we write in day to day programming matters more than we can ever think.

If you did started thinking like me, that whatever quick solves you did in day to day programming as dirty code, then I am sharing some of the references he pointed to me in references link. Please go and have a read of those. Otherwise, also thanks for you patience and interest in reading till now, and am sure one day or the other you will find it important and come back again.

In addition to this, I learnt the importance of Mathematics, and Progressions in programming, and am now confident of saying a good mathematician with a passion to program will become the “Real Developer of the World”. I did resolute to become more realistic developer, now its your turn.

References:

Raveendra Profile : http://in.linkedin.com/pub/raveendra-ch/2b/795/b5a/ 

Bill Gates on Programming : http://programmersatwork.wordpress.com/bill-gates-1986/

Posted in Uncategorized | Leave a comment

Singleton Pattern

As a programmer you should have come across many design patterns, in this blog entry I would like to spend some time on Singleton Design pattern. Before, further discussion on Singleton pattern, let us try understanding what is Design Pattern, and why do we need to learn about these patterns.

A Design pattern, is a specification defined to solve a particular problem. In our day to day programming we will be trying to solve several problems, design patterns are those solutions which are adopted by many developers around the globe to solve those specific problems you face today. Now its time for you to adopt some of those in your code, instead of fighting out your own solution for the problems you have on your table.

Below are few Design patterns, which were mostly adopted by many developers across the globe, in their day to day development.

  • MVC
  • Singleton
  • Factory Object
  • Builder
  • DAO pattern

Let us try to see the problem statements, that can be solved using the Singleton pattern and then we can dig more deeper on to what is a Singleton and what ways we can define singletons.

Problem Statement 1: My JVM goes OOM, because an object with heavy foot print is created several times, by several threads.

Problem Statement 2: I want a shared object across several threads during manipulation, without passing the references of that object.

Problem Statement 3: I want to define a utility class, but don’t want to create all the methods of that utility class as static.

If you, are stuck with any of the problem statements given above, then its time for you to implement a Singleton pattern for those objects. Now, that we know when to use a Singleton pattern, lets see what are its qualities, and what it offers for the developers.

  • Singleton objects can be instantiated only once
  • At any point of time there will be one and only one object in the JVM
  • All the threads will share the same object.

Now that, you have seen what all situations we can use Singleton, and what are the properties of a Singleton, let me show you how can we implement a Singleton pattern. A Singleton can be implemented using several techniques, I will try to cover some of those in this post.

1. Eager Instantiation

2. Lazy Instantiation

a. Locking

b. Double Checked Locking

c. Double Checked locking using volatile keyword

c. Using Inner Class

3. Using Enums as Singletons

Each of the above techniques with implementation details and examples, are explained hereunder, for giving you basic view of each of the technique.

Eager Instantiation:

Eager instantiation means, the object is initialized when the class is loaded, even before there is any actual invocation for getting a reference to that object. This method is not advisable, as you will be creating an object, even before it is needed for your application. If you object loaded this way, is a heavyweight object then you will be wasting a lot of Heap memory.

   1: public class Foo{

   2:     public static Foo foo = new Foo();

   3:     private Foo(){}

   4:     public static Foo getInstance(){

   5:         return foo;

   6:     }

   7: }

Lazy Instantiation:

Lazy instantiation means, the object is initialized when the application requires it, instead of creating at the time the Class is loaded on to the JVM. Lazy instantiation can be done in variety of ways, each having subtle problems which I will be explaining shortly.

Locking: In this method we will make the get Instance method synchronized, this will acquire a lock on the Class type, and any threads that want to access the methods of this class will be kept on waiting and the performance degrades at a high degree.

   1: public class Foo {

   2:     private Foo foo;

   3:     private Foo(){}

   4:     public static synchronized Foo getInstance(){

   5:        if(foo==null){

   6:          foo = new Foo();    

   7:         }

   8:         return foo;

   9:     }

  10: }

Double Checked Locking: In this method we will check whether the object is initialized before acquiring the lock, and again check whether any thread has completed the creation of the object after acquiring the lock, and then create an object.

   1: public class Foo{

   2:     private Foo foo;

   3:     private Foo() {}

   4:     public static foo getInstance(){

   5:         if(foo == null){

   6:             synchronized(foo){

   7:                 if(foo==null){

   8:                     foo = new Foo();

   9:                 }

  10:             }

  11:         }

  12:         return foo;

  13:     }

  14: }

In this approach, there is a limited possibility of error, that is when a Thread acquires a lock and a constructor is being called. Even before the completion of the constructor, another thread might request for getInstance and see that foo is not “null”, and hence returns a partially initialized object. These sort of partially initialized objects can break the system, and will be very hard to debug.

Double Checked Locking Using volatile: In this method we will be implementing the same Double Checked Locking pattern, while adding a keyword called volatile(Introduced in JDK 1.5) to the  object variable. Volatile keyword makes sure that there is no ThreadLocal copy of this variable, and hence will always reference to the same object though it is accessed by multiple threads.

   1: public Class Foo{

   2:     private volatile Foo foo;

   3:     private Foo(){}

   4:     public static foo getInstance(){

   5:         if(foo == null){

   6:             synchronized(foo){

   7:                 if(foo==null){

   8:                     foo = new Foo();

   9:                 }

  10:             }

  11:          }

  12:         return foo;

  13:     }

  14: }

Using Inner Class: In this method we use a Singleton Helper inner class to lazily load the object, which is guaranteed to have a single reference of it across all the threads.

   1: public class Foo{

   2:     private static class FooSingletonHelper{

   3:         private static Foo instance = new Foo();

   4:     }

   5:     private Foo(){]

   6:     public static Foo getInstance()[

   7:         return FooSingletonHelper.instance;

   8:     }

   9: }

I prefer, creating the Singleton objects using this Inner Class methods, since there is no need to explicitly handle the synchronization issues, and the job of creating and making sure that only instance of the object to the compiler.

Using Enums as Singletons:

Using Enum Singletons, is increasing in todays programming, as they are more Thread-safe, and again the job of creating an object is handled by the compiler itself. While we use the Enum’s, to mark types in java having some constants usage of enum as a singleton might not sound perfect for many reasons.

   1: public enum Foo{

   2:     Instance;

   3:     public void action(){

   4:         // perfrom an action

   5:     }

   6: }

 

Hope this article, has given some insights to you on Singleton pattern, and was a good read. The concepts, and examples I have given in the justification are based on my opinions and experience. I would really love to hear any comments or suggestions, so please give your feedback in the comments section.

References :

  • To know more about using Enums as Singletons, go through this link.
  • More about volatile keyword can be found here.
Posted in Uncategorized | Leave a comment

Novice Info: Difference between Classes, Interfaces in Java–Part 2

 

In my earlier post about Difference between Classes, Interfaces in Java I have explained about the differences in theory. Current post will be discussing about the practical differences that lets you make the decision on when to define a Class or Interfaces.

I am going to discuss about a 5 simple principles to be followed for creating a Class or an Interface. These principles will guide you in taking a right decision while defining the Types.

Rule 1: Define an Interface, when you want to create a contract between two subsystems

If you are developing an application, which involves interaction between two systems. Then creation of a contract, on how these two systems will communicate will help you minimize the complexity and enhances the maintainability.

Consider you have a Car Object and you have a subsystem that creates Breakes for your car. Due to upgrade in the technology & for safety it was mandated that all the Cars to have Disc/Power brakes. In this scenario if your Car Object is tightly coupled with the breaks object given by the sybsystem then you are mandated to upgrade the complete Car object. To avoid these scenarios you need to create subsystems based on a contract so that tey will be loosely coupled and the upgradation is simple.

   1: public class DrumBreakes{

   2:     public void applyBreaks(){

   3:         useDrumBreaks();

   4:     }

   5: }

   6:  

   7: public class Car{

   8:     DrumBreaks breaks = new DrumBreaks();

   9:     public void stop(){

  10:         breaks.applyBreaks();

  11:     }

  12: }

 

   1: public interface Break{

   2:     public void applyBreak();

   3: }

   4:  

   5: public class DrumBreak implements Break{

   6:     public void applyBreak(){

   7:         useDrumBreak();

   8:     }

   9: }

  10:  

  11: public class BreakFactory{

  12:     public enum BreakType{

  13:         Drum, Disc, Power, Air

  14:     }

  15:     private BreakFactory(){}

  16:     private static instance = new BreakFactory();

  17:     private static BreakFactory getInstance(){

  18:         return instance;

  19:     }

  20:     public Break getBreak(BreakType type){

  21:         Break breaks;        

  22:         switch(type){

  23:         case Drum:

  24:             breaks = new DrumBreak();

  25:             break;

  26:         case Disc:

  27:             breaks = new DiscBreak();

  28:             break;

  29:         case Power:

  30:             breaks = new PowerBreak();

  31:             break;

  32:         case Air:

  33:             breaks = new AirBreak();

  34:             break;

  35:         default:

  36:             breaks = new DiscBreak();

  37:             break;

  38:         }

  39:         return breaks;

  40:     }

  41: }

  42:  

  43: public class Car{

  44:     Break breaks = BreakFactory.getInstance().getBreaks(BreakType.Disc);

  45:     public void stop(){

  46:         breaks.applyBreak();

  47:     }

  48: }

  49:             

Rule 2: Define an Interface, when you want to create a Group of similar objects, Define an Interface to create several types with same behavior

   1: public interface Vehicle {

   2:     public void applyBreaks();

   3:     public void accelerate();

   4: }

   5:  

   6: public class Car{

   7:     @Override

   8:     public void applyBreaks(){

   9:         applyDiscBreak();

  10:     }

  11:     @Override

12: public void accelerate(){

  13:         frontWheelAcceleration();

  14:     }

  15: }

  16:  

  17: public class Bus{

  18:     @Override

  19:     public void applyBreaks(){

  20:         applyAirBreaks();

  21:     }

  22:     @Override

  23:     public void accelerate(){

  24:         backWheelAccelerate();

  25:     }

  26: }

In the above example Vehicle is an interface defined to group all the types that are having same behavior. Car & Bus are two types that are having same behavior. Hence they are grouped together with a type called Vehicle which defines a behavior that needs to be adhered by all its children.

   1: Vehicle car = new Car();

   2: Vechcle bus = new Bus();

The above construct holds true if and only if the grouping of these types are defined as stated above.

Rule 3: Define an Abstract Class, when you want to define a specific behavior for a Group of objects, Define an Abstract Class when want to have a generic behavior for all of your subtypes

   1: public abstract class Plant(){

   2:     public void createFood(){

   3:         photosynthesis;

   4:     }

   5:     public abstract void getFood();

   6: }

   7:  

   8: public class Hibiscus extends Plant{

   9:     @Override

  10:     public void getFood(){

  11:         fromFlower;

  12:     }

  13: }

  14:  

  15: public class Tomato extends Plant{

  16:     @Override

  17:     public void getFood(){

  18:         fromFruit;

  19:     }

  20: }

In the above example plant defines a generic behavior of doing photosynthesis, while each of its subtype uses this generic behavior to generate food of different types (Flower, Fruit).

Caution when defining subtypes by extending classes make a note of the java limitation that you will not be able to create a subtype inheritance from 2 or more classes. While you can create this type of multiple inheritance using Interfaces

Rule 4: Define a Class, when you have a fixed definition in your system.

   1: public class Car{

   2:     public void accelerate(){

   3:         use gas

   4:     }

   5:     public void stop(){

   6:         apply breaks

   7:     }

   8: }

   9:  

  10: public class TestCar{

  11:  

  12:     public static void main(String []aa){

  13:         Car car = new Car();

  14:         car.accelerate();

  15:         car.stoop();

  16:     }

  17: }

  18:      

Rule 5: Define a Final Class, if you don’t want the behavior to be overridden

Create a final class if and only if you do not want to create any subtypes of that type and the behavior should be overridden. An example of Final class in Java is java.lang.Math class.

All the above examples and explanations are just based on my views with my experience and should not be considered as concrete rules for designing a system.

Thanks for the interest on the content, and hope the information is helpful and useful. Do share your feedback in Comments section.

Posted in Uncategorized | Tagged , , , , , | Leave a comment

Novice Info: Difference between Classes, Interfaces in Java

Everyone of us, before writing a java program will create a Class and then add some methods to it. Before starting the conversation and going into the details of the differences between Classes and Interfaces, let us see the meaning, constructs / syntax of the Classes and Interfaces.

Class : A Java class is a virtual construct in Programming world, which can be instantiated to create Logical object to represent a Physical entity in the Virtual / Programming environment.
Every Object instantiated from a Class will have a state, and a behavior. These objects will communicate with other Objects in their virtual world using this behavior. We will take a deep dive about this communication between the objects in a short while.

Class Definition & Syntax:

   1: public class Vehicle { // syntax of class

   2: int steering; // these are the instance variables
   3: int wheels;
   4:
   5: Vehicle(int wheelCpunt){ // Is a constructor of the class
   6: wheels = wheelCount;
   7: }
   8: int getWheels(){
   9: return wheels;
  10: }
  11: }

In the above code snippet, public is a modifier and class keyword specifies that the Vehicle is a type of Class, and the second and third lines are having two variables, these are called instance variables and they hold the state of an object when instantiated.

The fifth line contains a Constructor for the class which will be called when an object is instantiated for the vehicle, and sets the state of the object by giving them the passed values or default values. In the above snippet when an Object of Vehicle is created, the state of wheels field is set by the parameter to the constructor, and the steering is given a default value which is 0 for an int.

There are 2 other types of classes, Inner Class and anonymous class, I will explain about them in the forth coming blog.

Interface : A Java Interface is also a virtual construct in programming world, but in contrary to the Java Class, Interface can not be instantiated or created as an object. An Interface denotes a group of logical entities. It can also act as a contract between two sub systems, while communicating with each other.

 
   1: public interface Vehicle{ // syntax of class

   2: int steeringCount = 2;
   3: int getWheels();
   4: }

 
The above code snippet, defines an interface called Vehicle. An interface will not have a constructor and cannot be instantiated or an object cannot be created for this type. The variables in an Interface are called Class variables / Static variables, since they cannot have instances they should be able to communicate using the Class Name itself. In addition to being a static variables these are also final by default which makes them not to be altered by any other objects.
 
Some of the differences between a class and an Interface
 
Property Class Interface

Instantiation

Can Be Instantiated

Can not be instantiated

State

Each Object created will have its own state

Each objected created after implementing will have the same state

Behavior

Every Object will have the same behavior unless overridden.

Every Object will have a define its own behavior by implementing the contract defined.

Inheritance

A Class can inherit only one Class and can implement many interfaces

An Interface cannot inherit any classes while it can implement many interfaces

Variables

All the variables are instance by default unless otherwise specified

All the variables are static final by default, and a value needs to be assigned at the time of definition

Methods

All the methods should be having a definition unless decorated with an abstract keyword

All the methods are abstract by default and they will not have a definition.

I hope this article was useful, and you did not find the time spent on this as useless. Please do share your comments and suggestions from the comments section.

Posted in Uncategorized | Leave a comment

Novice Info : Java Classes Demystified

In my previous post, I have explained about the differences between a Java Class and an Interface, in this post we are going to dwell deep into Java Classes. I will be covering the following concepts in this post.

  • What is a Class
  • What happens when you create an object of a Class
  • What are different types of classes in java
  • Generics in Classes

What is a Class :
“A class is the blueprint from which individual objects are created.” – as per the java tutorials in Sun oracle documentation.
Simply put, a class is a digital skeleton of an external world object, which can store the state, and has a definite behavior. Using this skeleton we can create many objects in the Virtual environment (JVM), all of these objects will have the same behavior, with a state of their own.
Difference between, class and Class : In java, “class” with a small “c” letter is a keyword that is used to define a skeleton/Blueprint. A “Class” with a capital “C” letter is a generic type, that is the name of the class, which is used to create objects.

   1: public class Car {

   2:  private String brand;
   3:  private String color;
   4:  public Car(String brand, String color){
   5:   this.brand = brand;
   6:   this.color = color;
   7:  }
   8:  public void drive(){
   9:   …
  10:  }
  11:  public void applyBreaks(){
  12:   …
  13:  }
  14:}

In the above Car Class, we have defined a couple of variables called “Brand”, “Color”. They store the state of the Car Objects. All the Car objects have a definite behavior that is defined as the methods “drive()”, “applyBreaks()”. The Car class is a logical structure of the real car entity.

The Objects created from the Car class (Skeleton) will have a state initialized at the time of creation of an Object for this class, using the constructor of the class (as shown in the code snippet below). Every Class defined with the “class” keyword, will have a Has-A relationship with the “Class” object in “java.lang” package.

Note : Class objects will created by the Classloader of the JVM, when an object of that type is instantiated.

What happens when you create an object of a Class

When an Object is created for any class, the JVM will create an Object for the Class(Car) type using the Classloader and then it will call the constructor to create a state for the object, and returns the reference of the object created for the Car type.

A Constructor is a way to create a new Object for any type. If there is no Constructor defined for the class, then the Compiler will add a default no-argument constructor into it. The first line of the Constructor has to be a “super()” or “this()” constructor. If there is no line like this, then the compiler will add the “super()” constructor by default. If a Constructor is defined, then the compiler will not add a no-arg constructor.

   1: /* Example 1 */

   2: public class Vehicle{
   3:    // Default Constructor with no arguments is added by default.
   4: }
   5: 
   6: 
   7: /* Example 2 */
   8: public class Vehicle{
   9:   public Vehicle(int wheels){
  10:      // Compiler will add a default super constructor
  11:     ….
  12:    }
  13:   /* No Arg Constructor need to be added if you need to when a
  14:   parameterized constructor is defined */
  15:   public Vehicle(){
  16:    this(4); /* super construtor will not be added as we have called this constructor */

  17:    }

  18: }

 

 What are different types of classes in java

  • Abstract Class
  • Inner Class
  • Local Class and Anonymous Class
  • Static Class

This section is to give an introduction to various types of classes and not a comprehensive set of the features, of these classes.

Abstract Class : An Abstract Class is a class, where they will have at least one abstract methods. (Abstract methods are the that has no definition / body). These classes cannot be instantiated (Objects for these classes cannot be created).

   1: public abstract class Vehicle{

   2:  public abstract void drive();
   3:  public void shiftGeat(){}; // This method is having the
   4: }

Inner Class : An Inner Class is a class defined with in a class.

   1: public class Vehicle{

   2:   …
   3:   public class Engine {
   4:     …
   5:   }
   6:     …
   7: }

Local Class and Anonymous Class:

Local classes are a special type of Inner classes, that are defined in the body of a method in a class. Similarly, Anonymous classes are a a type of Local Classes defined inside a method without a class name.

   1: public interface Event{

   2:   public abstract void action();
   3:   }
   4: 
   5:   public class Vehicle{
   6:   public void break(){
   7:      public class ABS extends Thread { // Local Class
   8:        ….
   9:      }
  10:     ABS abs = new ABS();
  11:     abs.start();
  12:   }
  13:  public void applyBreaks(){
  15:      Event e = new Event(){ // Anonymous Class
  16:      public void action(){
  17:      ABS abs = new ABS();
  18:      abs.start();
  19:      }       
  20:   };
  21:   e.action();
  22:  }
  23: }

 Generics in Classes

Generics in Classes, helps to identify the Cast errors at the compile time, instead of capturing it late at runtime. Generics again is a vast concept, which I feel might need its own blog, hence limiting the discussion about it to the basics.

Generics allows to pass Type parameters to the classes, and are defined to restrict the attempt of using it to ineligible objects.

   1: public Class Box<T> {

   2:    Map<T,Integer> tBox;
   3:    public Box(T t){
   4:      this.tBox = new HashMap<T,Integer>();
   5:    }
   6:    public void add(T t,int quantity){
   7:      tBox.put(t,quantity);
   8:    }
   9:    public Map<T,Integer> get(){
  10:     return this.tBox;
  11:    }
  12: }
  13: 
  14: public class TestBox{
  15:    public static void main(String[] aa){
  16:    Box<Chocolates> chocolateBox;
  17:    Box<Fruits> fruitBox;
  18:    choclateBox= new Box<Chocolates>();
  19:    fruitBox = new Box<Fruits>();
  20:    chocolateBox.add(Dairymilk,5);
  21:    chocolateBox.add(Cadbury,2);
  22:    chocolateBox.add(Apples,1); // Will throw a compile time error.
  23:    fruitBox.add(Apples,5);
  24:    fruitBox.add(Oranges,3);
  25:    chocolateBox = fruitBox.get(); // Will throw a compile tiime error.
  26:
  27: }

As shown in the above example, Box class ensures strict type checking with the objects created and hence will not result in any runtime issues, unless it is used in Raw type.

Hope, this is useful and you have got some information about the Java Classes. Please share your thoughts and suggestions in the comments section.

Posted in Uncategorized | Leave a comment