Inner Classes are those classes which are defined inside other class.
In simple word, the same manner in which a class contains a variable or method, a class can contain another class in it and these classes are known as INNER CLASSES.
InnerClassDemo.java
public class OuterClass
{
int i=;
public void m1()
{
System.out.println("I m in method m1");
}
class InnerClass
{
public void m2()
{
System.out.println("I m in method m2");
}
}
}
Code in red is the code of inner class and it is inside the boundary of the outer class(marked in blue);
Inner class can use all the variables and methods of outer class, even if they are private.
Inner class can use Outer Class data and vice versa.
Inner class is considered of nature useless because it is tightly bond to outer class and no other class can use it.
Inner Classes are used when a class require to implement same interface more than once.
Let us see a Swing application to demonstrate the use of INNER Class.
OnOffDemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class OnOffDemo extends JFrame
{
JButton jbtnOn,jbtnOff;
JTextField jtfStatus;
OnOffDemo()
{
super("Zartab Nakhwa");
setSize(500,500);
setDefaultCloseOperation(2);
setLocationRelativeTo(null);
Container c=getContentPane();
c.setLayout(null);
jtfStatus=new JTextField("");
jtfStatus.setBounds(100,50,300,100);
c.add(jtfStatus);
jbtnOn=new JButton("On");
jbtnOn.setBounds(100,250,150,30);
jbtnOn.addActionListener(new OnHandler());
c.add(jbtnOn);
jbtnOff=new JButton("Off");
jbtnOff.setBounds(300-30,250,150,30);
jbtnOff.addActionListener(new OffHandler());
c.add(jbtnOff);
setVisible(true);
}
public static void main(String args[] )
{
OnOffDemo app=new OnOffDemo();
}
class OnHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
jtfStatus.setText("ON");
}
}
class OffHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
jtfStatus.setText("OFF");
}
}
}
Here the piece of code marked in Purple and Green are two inner classes.
You might not require to instantiate an object of inner class, but still in case if you require,let have a close look at it.
class Demo
{
public static void main(String[] args)
{
OuterClass outer=new OuterClass();
OuterClass.InnerClass inner=outer.new InnerClass()
}
}
0 comments:
Post a Comment