Skip to main content

Inner classes & anonymous in java

Its block inside a class & behave as member of class.It doesn't just under package but under class of a package.Inner class have access to all members of outer class.

class class{
           inner class{
                 }
}

It not required to make an instance of an inner class in order to have an instance of the outer class but to get instance of inner class we need to create instance of outer class & via it we can create instance of inner class.



Inner class type

Static ( inner class having static modifer)
Member inner class ( normal class inside class)
Method Local ( inner class defined inside a method  of class)
Anonymous  ( inner class having no name)

  

1. Member inner class

From inside outer class inner class can be access like normal class see example as below.


//outer class declaration
class MyOuterClass {
private int i = 18;

// Creating instance of inner class and calling inner class function


public void createInnerInstance() {
// access inner class as normal if you are under scope of outer class
MyInnerClass inn1 = new MyInnerClass();  
inn1.getValue();
}

// inner class declarataion
class MyInnerClass {
public void getValue() {
// accessing private variable from outer class
System.out.println("value of i -" + i);
}
}



From outside of outer class function create instance of outer class then create instance of inner class to access any of its method. you can see that in below example.

class Test{
public static void main(string args[]){

MyOuterclass myouterclass = new MyOuterclass();
MyOuterclass.MyInnerclass  myinnerclass = MyOuterclass().new MyInnerclass ();

myinnerclass .getValue();

}}



this” keyword will refer the curren executing inner class Object. But to get this for outer class will need to use “OuterClass.this”.



2. When Inner class is inside method of class rather then class itself its called Method local inner class. Final & Abstract are the only modifiers available for this type of inner class.




class MyOuterClass {
private int i = 18;

public void methodOuterclass(){

// inner class declarataion
class MyInnerClass {
public void getValue() {
System.out.println("value of i -" + i);
}

//inner class instance creation
InnerClass localinner1 = new InnerClass();
localinner1.getValue();
}
 }



scope of the inner class is restricted within the method.
Method local inner class can not use the local variable defined in method While it can use the instance variable



When inner class don't have name its called anonymous inner class. as well as Inner classes having Static modifier are known as Static inner class.


static inner class cannot access non static member of outer class. Due to static in nature it can be created without creating instance of outer class like
MyOuter.MyInner i = new MyOuter.MyInner(); 

inner class cannot declare any static members unless they are compile-time constants and are primitives or Strings.




3. Anonymous inner class


public class AnonymousClassDemo
{
  public static void main(String[] args)
  {
    Fruit fruit= new Fruit() {
      public void someFruit ()
      {
        System.out.println("Anonymous Fruit");
      }   
    }; // anonymous class body closes here
    //fruit contains an object of anonymous subclass of Fruit.
    fruit.someFruit();
  }
}
 
class Fruit
{
  public void someFruit()
  {
    System.out.println("Organic Fruit");
  }
}


This is the functionality of defining an anonymous inner class because we want to override one or more methods of the super class on the fly.
anonymous inner classes can either implement an interface or extend a class, they can't do both at the same time. There is no such mechanism by which an anonymous inner class can implement multiple interfaces



4. Static Inner classes or Nested Static class

This is same as the Normal regular Innerclass, but it has the static members available .
Only static members of Outer class is directly accessible in nested static class. If we want to create the Inner Class Object no need to depend on the Outer Class Object


class Test{
public static void main(string args[]){

MyOuterclass myouterclass = new MyOuterclass(); Not required Here

//see the difference where earlier we have intsntiated normal member inner class.
MyOuterclass.StaticInnerclass  myStaticInnerclass = new StaticInnerclass.MyInnerclass ();
myStaticInnerclass.getValue();

}}


Nested static class doesn’t need reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.







Comments

  1. perfect explanation about java programming .its very useful.thanks for your valuable information.java training in chennai | java training in velachery

    ReplyDelete
  2. Nice tutorial about Java Inner Class .
    thanks for this nice post.

    ReplyDelete

Post a Comment

Popular posts from this blog

Conversion from Clob To String in java and Vice versa

/***reading Clob data from oracle table and setting to Pojo**/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import oracle.sql.CLOB;

import com.poc.one.pojo.StagedMessage;

public class MessageDao {
private static String url = "jdbc:oracle:thin:@172.22.22.198:1521:ORACLE";
private static String username = "ABC123";
private static String password = "ABC123";


public  List readClobToBO() throws Exception {

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn
.prepareStatement("SELECT ID, STORE_ID, MESSAGE_DATA FROM STAGED_MESSAGE ");
ResultSet resultSet = stmt.executeQuery();
List msgList= new ArrayList();

while (resultSet.next()) {

StagedMessage message = new StagedMessage();

message.setId(resultSet.getInt(1));
message.setStoreId(r…

Portable Java 8/ JDK8 setup without admin rights

Some time we got machine to work where we don't have access rights to install anything or if you do not want to install. You can get latest jdk running by this trick. Just follow step step & do comment if you like it.

Step by Step details to get running java from .exe setup without any admin rights. Get portable 7 zip from portableapps.comdownload java 8 from oracle  http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.htmlopen 7 zip & extract jdk-8u102-windows-x64.exeyou will see below folders                .data                .pdata                .rdata                .reloc                .rsrc                .text                CERTIFICATE

          5.Go inside E:\jdk-8u102-windows-x64\.rsrc\1033\JAVA_CAB10you will find 111 file.

         6.extract it it some folder where you can find tools.zip again extract that to some folder say Java & copy it to very first folder of setup along with .data,.rsrc etc.
         7.Go to folder where you have co…

Multi Threading , Producer consumer problem in Java

Multi threading is topic which is always fascinating for java developer. I feel its more about practical the theory. So here i wanted to present sample examples which clear understanding for several multi threading concept.

In Theory basically thread which is light weight process.Thread shares mostly same memory space.
I said mostly because there is some space called thread local which is not common to threads & separate for each thread. We create thread whenever we wanted to use multicore of processor although that doesn't mean single core cant use it. In single core context switching works among different running thread.

for example suppose there is website which is showing latest price as well as offer as well as doing order booking all these things can be assigned to different thread to provide parallel processing.



There are 2 ways for creating a thread.

Extend a thread & Implement a Runnable class. Extending a class is little avoided since it closed possibility for e…