Friday, January 31, 2014

Abstract Classes vs Interfaces in Java

Abstract Classes vs Interfaces in Java
Everybody knows that in abstract class we can define method body but not in interface, but there are more difference between abstract class and interface. For instance, now in Java 8 we can have default as well as static method in interface. In this post, we look in the difference between them as well as from Java 8 perspective and also the basic knowledge when to use abstract and interface.



   Abstract Classes Interfaces
Keyword(s) used Use the abstract and class keywords to define a class Use the interface keyword to define an
interface.
Keyword used by the
implementing class
Use the extends keyword to inherit from an abstract class Use the implements keyword to implement an
interface.
Default implementation An abstract class can provide default implementation of methods You cannot define methods in an interface; you
can only declare them.
Fields An abstract class can have static and non-static members You cannot have any instance variables
in an interface
Constants An abstract class can have both static (using static and final keyword) and non-static (using final keyword) constants declarations Interfaces can contain constant declarations If you
declare a field, it must be initialized. All fields are implicitly considered to be declared as public
static and final.
Constructors You can define a constructor in an abstract class (which is useful for initializing fields, for example). You cannot declare/define a constructor in an
interface.
Access specifiers You can have private and protected
members in an abstract class.
You cannot have any private or protected members
in an interface; all members are public by default.
Single vs. multiple
inheritance
A class can inherit only one class (which can be either an abstract or a concrete class). A class can implement any number of interfaces.
is-a relationship vs.
following a protocol
An abstract base class provides a protocol; in addition, it serves as a base class in an is-a relationship. An interface provides only a protocol.
It specifies functionality that must be
implemented by the classes implementing it
Default implementation
of a method
An abstract class can provide a default
implementation of a method. So, derived
class(es) can just use that definition and
need not define that method
An interface can only declare a method. All
classes implementing the interface must
define that method.
Difficulty in making changes It is possible to make changes to the implementation of an abstract class. For
example, you can add a method with default implementation and the existing derived classes will not break.
If there are already many classes implementing
an interface, you cannot easily change that
interface. For example, if you declare a new
method, all the classes implementing that
interface will stop compiling since they do not
define that method but it is possible with default method of Java 8

Java 8 update : Interface now contain default and static methods. 

Choosing Between an Abstract Class and an Interface

  • If you are identifying a base class that abstracts common functionality from a set of related classes, you should use an abstract class. If you are providing common method(s) or protocol(s) that can be implemented even by unrelated classes, this is best done with an interface.
  • If you want to capture the similarities among the classes (even unrelated) without forcing a class relationship, you should use interfaces. On the other hand, if there exists an is-a relationship between the classes and the new entity, you should declare the new entity as an abstract class.


Consider using abstract classes if any of these statements apply to your situation:
  • You want to share code among several closely related classes.
  • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

Consider using interfaces if any of these statements apply to your situation:
  • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
  • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
  • You want to take advantage of multiple inheritance of type.

JDK example:
An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines.

An example of a class in the JDK that implements several interfaces is HashMap, which implements the interfaces Serializable, Cloneable, and Map<K, V>. By reading this list of interfaces, you can infer that an instance of HashMap (regardless of the developer or company who implemented the class) can be cloned, is serializable (which means that it can be converted into a byte stream; see the section Serializable Objects), and has the functionality of a map. In addition, the Map<K, V> interface has been enhanced with many default methods such as merge and forEach that older classes that have implemented this interface do not have to define.

Example :
Let’s look at an example of choosing between abstract classes and interfaces in the Paint application. You can have Shape as an abstract base class for all shapes (like Circle, Square, etc.); this is an example of an is-a relationship. Also, common implementations, such as parent shape , can be placed in Shape. Hence, Shape as an abstract class is the best choice in this case.

In Paint, the user can perform various actions on shape objects. For example, a few shapes can be rotated, and a few can be rolled. A shape like Square can be rotated and a shape like Circle can be rolled. So, it does not make sense to have rotate() or roll() in the Shape abstract class. The implementation of rotate() or roll() differs with the specific shape, so default implementation could not be provided. In this case, it is best to use interfaces rather than an abstract class.




If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Everything about Interface in java

In this post, we will see what is an Interface, how to declare it and how to use polymorphically. We will also see new updates about interface in Java 8 and why Java developers have introduced method body in interface in Java 8? Moreover, What will be the use of method body in interface?


Interface
General definition: an interface refers to a common boundary or interconnection between two entities.
For instance, a keyboard in a computer system provides an interface between a human being and the computer. A natural language such as English is an interface between two humans that allows them to exchange their views.

Java definition: Interfaces are like a  100-percent abstract superclass that defines the methods a subclass must support, but not how they must be supported.

In Java, an interface is a set of abstract methods that defines a protocol (i.e., a contract for conduct). Classes that implement an interface must implement the methods specified in the interface. 
An interface defines a protocol, and a class implementing the interface honors the protocol. In other words, an interface promises a certain functionality o its clients by defining an abstraction. All the classes implementing the interface provide their own implementations for the promised functionality.

In other words, an Animal interface might declare that all Animal implementation classes have an eat() method, but the Animal interface doesn't supply any logic for the eat() method. That means it's up to the classes that implement the Animal interface to define the actual code for how that particular Animal type behaves when its eat() method is invoked.

interface Animal{  
      void eat();  
      abstract void walk();  
 }  
 class Lion implements Animal {  
      @Override  
      public void eat() {  
           System.out.println("lion eating");  
      }  
      @Override  
      public void walk() {  
           System.out.println("lion running fast");  
      }  
 }  
 public class AnimalInterfaceDemo{  
      public static void main(String javalatte[]){  
           Lion l = new Lion();  
           l.walk();  
           l.eat();  
      }  
 } 


Example :


public interface Comparable{  
 public int compareTo(Object o);  
 // Intent is to compare this object with the specified object  
 // The return type is integer. Returns negative,  
 // zero or a positive value when this object is less than,  
 // equal to, or greater than the specified object  
 } 

Unrelated classes can provide their own implementations when they implement Comparable. These unrelated classes have one aspect in common: they all follow the specification given by Comparable, and it is left to the implementation of these individual classes to implement compareTo() accordingly.

Conceptually, a class and an interface are two different constructs used for two different purposes. A class combines the state and the behavior of a real object, whereas an interface specifies the behavior of an abstract entity.

How to declare interface
When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. An interface is a contract.
Interfaces can be implemented by any class, from any inheritance tree. This lets you take radically different classes and give them a common characteristic.
Think of an interface as a 100-percent abstract class. Like an abstract class,an interface defines abstract methods that take the following form:
     abstract void bounce();
But while an abstract class can define both abstract and non-abstract methods, an interface can have only abstract methods.

Some point to remember about interface
  • An interface cannot be instantiated.
  • All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
    public abstract interface Rollable { }
    public interface Rollable { }

    Both of these declarations are legal, and functionally identical.
  • All variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants (means public static final) , not instance variables.
  • Interface methods must not be static.
  • Because interface methods are abstract, they cannot be marked final, strictfp, or native
  • An interface can extend one or more other interfaces.
  • An interface cannot extend anything but another interface.
  • An interface cannot implement another interface or class.
  • An interface must be declared with the keyword interface.
  • Interface types can be used polymorphically
  • An interface can be declared within another interface or class; such interfaces are known as nested interfaces.
You must remember that all interface methods are public and abstract regardless of what you see in the interface definition.


How to declare interface constants(means public static final)
You're allowed to put constants(means public static final) in an interface. By doing so, you guarantee that any class implementing the interface will have access to the same constant.
By placing the constants right in the interface, any class that implements the interface has direct access to the constants, just as if the class had inherited them.
You need to remember one key rule for interface constants. They must always be
public static final

interface constants{  
      int MAX = 10;  
      public static final int MIN = 2;  
 }  
 public class InterfaceConstant implements constants{  
      public static void main(String javalatte[]){  
           System.out.println("MIN = "+MIN+" MAX = "+MAX);  
      }  
 } 

You can't change the value of a constant!(means public static final declared variable) 

How Interface types can be used polymorphically
Let's say we have class Duck who can swim and quack. Whatever duck class extend this class, they have the functionality of swim and quack.
It looks like

class Duck{  
      public void swim(){  
           System.out.println("I'm swiming");  
      }  
      public void quack(){  
           System.out.println("quacking......");  
      }  
 }  
 class MallardDuck extends Duck{  
      // it has both functionality of swim and qauck  
 }  
 class RedHeadDuck extends Duck{  
      // it has both functionality of swim and qauck  
 }

Now suppose later, we want the fly functionality as per OO we simply add fly() method in the duck class and then all the ducks will inherit it.

class Duck{  
      public void swim(){  
           System.out.println("I'm swiming");  
      }  
      public void quack(){  
           System.out.println("quacking......");  
      }  
      public void fly(){  
           System.out.println("flying.....");  
      }  
 }

By adding the fly behavior in the superclass can't not be appropriate for some Duck subclassess. For instance, RubberDuck extends Duck class.

class RubberDuck extends Duck{  
      public void quack(){  
           System.out.println("squeak......");  
      }  
      //It can't fly  
 }

It will become worse of WoodDuck extends Duck class as it can't fly and swim.
In this case, the use of inheritance for the purpose of reuse hasn't turned out so well when it comes to maintenance.

Now we take the fly() out of the Duck superclass and make a Flyable interface with a fly method. That way, only the ducks that are supposed to fly will implements that interface and have a fly method.
This is one of the design principle : Identify the aspects of your application that vary and separate them from what stays the same.

A reference variable can be declared as a class type or an interface type. If the variable is declared as an interface type, it can reference any object of any class that implements the interface.

class Duck{  
      public void swim(){  
           System.out.println("I'm swiming");  
      }  
      public void quack(){  
           System.out.println("quacking......");  
      }  
 }  
 interface Flyable {  
      void fly();  
 }  
 class RubberDuck extends Duck{  
      public void quack(){  
           System.out.println("squeak......");  
      }  
 }  
 class MallardDuck extends Duck implements Flyable{  
      @Override  
      public void fly() {  
           System.out.println("MallardDuck flying");  
      }  
 }  
 class RedHeadDuck extends Duck implements Flyable{  
      @Override  
      public void fly() {  
           System.out.println("RedHeadDuck flying");  
      }  
 }  
 public class PolymorphicallyInterfaceDemo {  
      public static void main(String javalattep[]){  
           Flyable f = new RedHeadDuck();  
           f.fly();  
           f = new MallardDuck();  
           f.fly();  
           RedHeadDuck r = new RedHeadDuck();  
           r.fly();  
      }  
 }


Q. What will happen if class implement two interface having common method?
Ans:
That would not be a problem as both are specifying the contract that implement class has to follow.
If class C implement interface A & interface B then Class C thing I need to implement print() because of interface A then again Class think I need to implement print() again because of interface B, it sees that there is already a method called test() implemented so it's satisfied.

interface A{  
      void print();  
 }  
 interface B{  
      void print();  
 }  
 class C implements A,B{  
      @Override  
      public void print() {  
           System.out.println("java-latte.blogspot.in");  
      }  
 }  
 public class TwoInterfaceDemo {  
      public static void main(String javalatte[]){  
           C c = new C();  
           c.print();  
      }  
 }  


Most of the time we'll think why interface has no body and what if it has body what will be merits and demerits that we'll see in the next section as per draft version of Java 8.

The Interface Body in Java 8
The interface body can contain abstract methods, constants variabledefault methods, and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation). 
Default methods are defined with the default modifier, and static methods with the static keyword. All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

In addition, an interface can contain constant(means public static final) declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, you can omit these modifiers.


Drawback of interface
Consider an interface that you have developed called Animal:

public interface Animal {  
   void eat();  
   int weight(String s);  
 }

Suppose that, at a later time, you want to add a third method to Animal, so that the interface now becomes:

public interface Animal {  
   void eat();  
   int weight(String s);  
   void swim();  
 }

If you make this change, then all classes that implement the old Animal interface will break because they no longer implement the old interface. Programmers relying on this interface will protest loudly

Default method in interface

If you want to add additional methods to an interface, you have several options.
You could create a AnimalSwim interface that extends Animal:

public interface AnimalSwim extends Animal {  
   boolean swim();    
 } 

Now users of your code can choose to continue to use the old interface or to upgrade to the new interface.

Alternatively, you can define your new methods as default methods. The following example defines a default method named swim:

public interface Animal {  
   void eat();  
   int weight(String s);  
   default void swim() {  
     // Method body   
   }  
 }

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

  • You specify that a method definition in an interface is a default method with the default keyword at the beginning of the method signature. 
  • All method declarations in an interface, including default methods, are implicitly public, so you can omit the public modifier.

Extending Interfaces That Contain Default Methods
When you extend an interface that contains a default method, you can do the following:
  • Don't mention the default method,and lets your extend interface inherit the default method.
  • You can redeclare the default method which make them abstract again. Similary, when abstract class extend abstract class.
  • You can redefine the default method similar to overriding.

QAgain one question come to mind that if two interface are providing default method with similar signatures and class is extending both the interface, will it not be again diamond problem?
Yes, you are thinking right but Java doesn't allow you to implement interface with has same default method.

Static Methods in interface
In addition to default methods, you can define static methods in interfaces
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.
This makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class.

interface stack{  
      void push(int i);  
      int pop();  
      int peek();  
      static calculateElement(StackImp st){  
           // code to calculate the no of element in stack  
      }  
 }


Like static methods in classes, you specify that a method definition in an interface is a static method with the static keyword at the beginning of the method signature. All method declarations in an interface, including static methods, are implicitly public, so you can omit the public modifier.

Interface in Java 9(update)
As you seen earlier, you can define abstract methodsconstants variabledefault methods, and static methods in java 8. Now with Java 9, you can define private methods and private static methods 
Question arise, why private methods? As you can define default functionality in defaults methods that will be available to all the class who implements the interface. In static methods, we write some helper method so that it specific to interface. However, when we need to define some common functionality that is only specific to interface and no class can inherit that such as connection to logging,opening a file etc. so that it can be only used inside interface. That means no duplicate code and we can control what we want to expose to the client.


In order to write private method in interface, just use private identifier and must write the body




If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Tuesday, January 21, 2014

What is the Static Keyword in Java

In this post, we'll see the use of static keyword in various locations including what can be marked static or not in Java and how static creation  differ from normal object creation.




The static modifier is used to create variables and methods that will exist independently of any instances created for the class.

All static members exist before you ever make a new instance of a class, and there will be only one copy of a static member regardless of the number of instances of that class.

In other words, all instances of a given class share the same value for any given static variable.








Things you can mark as static:
  • Methods
  • Variables
  • A class nested within another class, but not within a method.
  • Initialization blocks


Things you can't mark as static:
  • Constructors (makes no sense; a constructor is used only to create instances)
  • Classes (unless they are nested)
  • Interfaces
  • Method local inner classes
  • Inner class methods and instance variables
  • Local variables


The way a static member works
Imagine you've got a utility class with a method that always runs the same way; its sole function is to return, say, a random number.
It wouldn't matter which instance of the class performed the method—it would always behave exactly the same way. In other words, the method's behavior has no dependency on the state (instance variable values) of an object.
So why, then, do you need an object when the method will never be instance-specific?
Why not just ask the class itself to run the method?

Suppose you want to keep a running count of all instances instantiated from a particular class. Where do you actually keep that variable? 
It won't work to keep it as an instance variable within the class whose instances you're tracking, because the count will just be initialized back to a default value with each new instance.

Static variable
Static variables belong to a class. They are common to all instances of a class and aren’t unique to any instance of a class. static attributes exist independently of any instances of a class and may be accessed even when no instances of the class have been created. You can compare a static variable with a shared variable. A static variable is shared by all of the objects of a class.

Think of a static variable as being like a common bank vault that’s shared by the employees of an organization. Each of the employees accesses the same bank vault, so any change made by one employee is visible to all the other employees

Variables and methods marked static belong to the class, rather than to any particular instance. In fact, you can use a static method or variable without having any instances of that class at all.
You need only have the class available to be able to invoke a static method or access a static variable. static variables, too, can be accessed without having an instance of a class. 
But if there are instances, a static variable of a class will be shared by all instances of that class; there is only one copy.

Sample Output:
counter : 3

A static method can't access a nonstatic (instance) variable, because there is no instance!
That's not to say there aren't instances of the class alive on the heap, but rather that even if there are, the static method doesn't know anything about them. The same applies to instance methods; a static method can't directly invoke a nonstatic method

Think static = class, nonstatic = instance.

Making the method called by the JVM (main()) a static method means the JVM doesn't have to create an instance of your class just to start running code.

One of the mistakes most often made by new Java programmers is attempting to access an instance variable (which means nonstatic variable) from the static main() method.

Example of this:


How to access Static Methods and Variables
  • Static variables have the longest scope; they are created when the class is loaded, and they survive as long as the class stays loaded in the Java Virtual Machine

We know that with a regular old instance method, you use the dot operator on a reference to an instance. For instance,

In this code, we instantiated a StaticAccess and assign it to the reference varialble sa and then use that sa to invoke method on the StaticAccess instance. 
In other words, the getSize() method is invoked on a specific StaticAccess object on the heap.

But this approach (using a reference to an object) isn't appropriate for accessing a static method, because there might not be any instances of the class at all.
That's the reason main method is always static.

So, the way we access a static method (or static variable) is to use the dot operator on the class name, as opposed to using it on a reference to an instance. For example,

The Java language also allows you to use an object reference variable to access a static member but later this is discouraged.

This is merely a syntax trick to let you use an object reference variable (but not the object it refers to) to get to a static method or variable, but the static member is still unaware of the particular instance used to invoke the static member. 


In the StaticVariableAccess example, the compiler knows that the reference variable sva is of type StaticVariableAccess, and so the StaticVariableAccess class static method is run with no awareness or concern for the StaticVariableAccess instance at the other end of the sva reference. 
In other words, the compiler cares only that reference variable sva is declared as type StaticVariableAccess.

Finally, remember that static methods can't be overridden! This doesn't mean they can't be redefined in a subclass, but redefining and overriding aren't the same thing.

The distinction between hiding a static method and overriding an instance method has important implications:

  • The version of the overridden instance method that gets invoked is the one in the subclass.
  • The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.


Initialization blocks
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {  
   // whatever code is needed for initialization goes here  
 }

  • A class can have any number of static initialization blocks, and they can appear anywhere in the class body.
  • The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
  • A static initialization block runs once, when the class is first loaded it's means after a considerable amount of time after the class is loaded as Java make a distinction between class loading and class initialization.( thanks of Lew Bloch for making it more clear) It.An instance initialization block runs once every time a new instance is created.

Sample Output:

block 1
block 2
block 3
main()



Static Nested Classes
Static nested classes referred to as static inner classes  but they really aren't inner classes at all, by the standard definition of an inner class.

While an inner class enjoys that special relationship with the outer class (or rather the instances of the two classes share a relationship), a static nested class does not.
It is simply a non-inner (also called "top-level") class scoped within another. So with static classes it's really more about name-space resolution than about an implicit relationship between the two classes.

A static nested class is simply a class that's a static member of the enclosing class:


class BigOuter {  
   static class Nested { }  
 }  
The class itself isn't really "static"; there's no such thing as a static class. 
The static modifier in this case says that the nested class is a static member of the outer class. That means it can be accessed, as with other static members, without having an instance of the outer class.

Sample Output
static inner class
static inner class 2




If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Sunday, January 12, 2014

Final keyword examples in Java

In this post, we see the different use of final keyword when it's applied to class, methods and variables.


Final Classes


Final methods


Final variables


Final Objects


Final Arguments



Final classes
A final class is a non-inheritable class—that is to say, if you declare a class as final, you cannot subclass it.In other words, no other class can ever extend (inherit from) a final class, and any attempts to do so will give you a compiler error.

So why would you ever mark a class final? After all, doesn't that violate the whole object-oriented (OO) notion of inheritance?

In some cases you don’t want to allow a class to be sub classed. Two important reasons are
  • To prevent a behavior change by sub-classing. In some cases, you may think that the implementation of the class is complete and should not change. If overriding is allowed, then the behavior of methods might be changed. You know that a derived object can be used where a base class object is required, and you may not prefer it in some cases. By making a class final, the users of the class are assured the unchanged behavior
  • Improved performance. All method calls of a final class can be resolved at compile time itself. As there is no possibility of overriding the methods, it is not necessary to resolve the actual call at runtime for final classes, which translates to improved performance. For the same reason, final classes encourage the inlining of methods. If the calls are to be resolved at runtime, they cannot be inlined.

You'll notice many classes in the Java core libraries are final. For example, the String class cannot be subclassed. Imagine the havoc if you couldn't guarantee how a String object would work on any given system your application is running on! 
So use final for safety, but only when you're certain that your final class has indeed said all that ever needs to be said in its methods. Marking a class final means, in essence, your class can't ever be improved upon, or even specialized, by another programmer.

Another example, java.lang.System. These classes are used extensively in almost all Java programs. For example, if you use a System.out.println() statement, you are using both the System class as well as the String class since println takes String as an argument.If these two classes are not declared final, it is possible for someone to change the behavior of these classes by subclassing and then the whole program can start behaving differently

A benefit of having nonfinal classes is this scenario
Imagine you find a problem  with a method in a class you're using, but you don't have the source code. So you can't modify the source to improve the method, but you can extend the class and override the method in your new subclass, and substitute the subclass everywhere the original superclass is expected. If the class is final, though, then you're stuck.


Final Methods
In a class, you may declare a method final. The final method cannot be overridden. Therefore, if you have declared a method as final in a non-final class, then you can extend the class but you cannot override the final method. But, other non-final methods in the base class can be overridden in the derived class implementation.
It often used to enforce the API functionality of a method.
For example, the Thread class has a method called isAlive() that checks whether a thread is still active. If you extend the Thread class, though, there is really no way that you can correctly implement this method yourself (it uses native code, for one thing), so the designers have made it final.
Just as you can't subclass the String class you can't override many of the methods in the core class libraries.
class test{  
      final void print(){  
           System.out.println("hello test");  
      }  
 }  
 public class FinalMethodOverride extends test{  
      void print(){ // error  
           System.out.println("Hello overloaded test");  
      }  
 }  

Final variables
Using the "final" keyword makes the the variable you are declaring immutable. Once initially assigned it cannot be re-assigned.

Final variables are like CD-ROMs: once you write something on them, you cannot write again. In programming, universal constants such as PI can be declared as final since you don’t want anyone to modify the value of such constants. Final variables can be assigned only once. If you try to change a final variable after initialization, you will get a complaint from your Java compiler.
public class FinalVariable{  
      public static void main(String javalatt[]){  
           final int i = 10;  
           i = 10; // error  
      }  
 } 


Reasons why you would use the "final" keyword on variables
  • Optimization where by declaring a variable as final allows the value to be memoized
  • You would use a final variable is when an inner class within a method needs to access a variable in the declaring method.
Example
public class FinalVarialbeOne {  
      public static void main(String java[]){  
           new Hello().go();  
      }  
      public void go(){  
           final int counter = 5;  
           new Runnable() {  
                @Override  
                public void run() {  
                     int i = counter;  
                     System.out.println("i="+i);  
                }  
           }.run();  
      }  
 }  
Sample Output

i=5



Final Object
The value of a final parameter cannot be changed once assigned. Here, it is important to note that the “value” is implicitly understood for primitive types. However, the “value” for an object refers to the object reference, not its state.
class Test2{  
      private int i = 10;  
      void setValue(int i){  
           this.i=i;  
      }  
      int getValue(){  
           return this.i;  
      }  
 }  
 public class FinalMethodOverride extends test{  
      public static void main(String javalatte[]){  
           final Test2 ts1 = new Test2();  
           ts1.setValue(100);  
           ts1 = new Test2(); //error   
      }  
 }  
If an object is final you can call any methods that do internal changes as usual, but you cannot reassign the reference to point to a different object


Final Arguments
Method arguments are the variable declarations that appear in between the parentheses in a method declaration.

public void sum(int a, final int b)

In this example, the variable b is declared as final, which of course means it can't be modified within the method. In this case, "modified" means reassigning a new value to the variable. In other words, a final argument must keep the same value that the parameter had when it was passed into the method.


Points to Remember

  • Final stop value change.
  • Final stop method overriding.
  • Final stop inheritance.
  • The final modifier can be applied to a class, method, or variable. All methods of a final class are implicitly final (hence non-overridable).
  • A final variable can be assigned only once. If a variable declaration defines a variable as final but did not initialize it, then it is referred to as blank final. You need to initialize a blank final all the constructors you have defined in the class; otherwise the compiler will complain.
  • The keyword final can even be applied to parameters. The value of a final parameter cannot be changed once assigned. Here, it is important to note that the “value” is implicitly understood for primitive types. However, the “value” for an object refers to the object reference, not its state. Therefore, you can change the internal state of the passed final object, but you cannot change the reference itself.



If you know anyone who has started learning java, why not help them out! Just share this post with them. 
Thanks for studying today!...