Você está na página 1de 30

Inner classes, Local classes,

Anonymous classes

More ways to organize code


Inner, local and anonymous classes

•  This lecture is about three new ways of


organizing code:
– inner classes: classes inside other classes
– local classes: classes inside methods
– anonymous classes: classes with no name

2
Members of a class
•  The definition of a class looks like:

public class SomeThing


{
int field1; //privacy not specified
String field2;

public void method1(String s)


{…}
}

3
Class = collection of members

•  This definition is really just a collection of


members of the class:
–  fields
–  methods
•  Each non-static member has an
incarnation inside every object of the
class.

4
Inner classes

•  Inner classes are classes that are members


of other classes.
•  To write an inner class, just write a class
inside another class.
•  Like fields and methods, you get one
version of the inner class for every
object of the outer class.

5
Example
class OuterClass {
int myField;
// add some methods here

class InnerClass {
int anotherField;
int answer()
{
return (myField + anotherField);
}
}
}

NOTE: Could/should have used visibility modifiers e.g. private etc!!


6
Points to notice

•  Because the inner class is a member of


OuterClass, it can access other members
(like the field myField) directly.
•  To access InnerClass, you need to be able
to access an object of type OuterClass.
•  Usually you access InnerClass only from
within OuterClass.

7
Concrete example: a listener
public class SimpleGUI extends JFrame
{
JButton button;
JTextField output;

public void init()


{
// set up a GUI
button = new JButton("press me");
button.addActionListener(new InnerListener());
}

8
The listener itself

public class InnerListener implements ActionListener {
public void actionPerformed(ActionEvent e)
{
output.setText("Event handled");
}
}
… more SimpleGUI code, if needed
}

9
A nice design!
•  This is a nice design:
–  the listener class is genuinely part of the GUI
class, which makes sense
–  there is no need to pass references around to
give the listener access to the GUI
components.
•  Note that the GUI components are stored
in fields of the outer class, not local
variables in init().
10
Many nested inner classes…

•  You can have as many inner classes as


you like, although of course they have to
have different names.
•  You can even have classes within classes
within classes within classes… although I
am not sure why you would want that.

11
Local variables
•  Recall that as well as fields (variables
which are members of a class), we have
local variables, which live inside
methods, or smaller code-blocks.

public boolean isThisClear()


{
boolean answer = true;
return answer;
}

12
Scope of local variables

•  Local variables are only visible inside the


block (the { … }) where they are declared.
•  They appear when they are declared, and
vanish again when the block is finished.
•  This is called their scope.

13
Local classes

•  We have seen
–  ordinary classes
–  inner classes, which are members of other
classes.
•  We can also have local classes, which live
inside a method body.

14
Example
public void doSomething()
{
int localVariable;

class LocalClass extends SomeClass {


// class definition here.
}
}

15
Local classes for listeners
•  It can sometimes be useful to use a local
class when writing a listener.
•  A local class has access to the fields and
methods of the main class, just like any
code in a method would do.
•  It also has access to other local variables
of the method, as long as they are declared
final.

16
Concrete example
public class SimpleGUI extends JFrame {
JButton button;
JTextField output;

public void init() {


// set up a GUI
button = new JButton("press me");

17
Example continued
class LocalActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
output.setText("I handled the event");
}
}

button.addActionListener(new LocalActionListener());
… rest of init() method…
}
… rest of class …

18
Points to note

•  Again the local class can access the fields


of the outer class directly, so there's no
need for that reference passing business.
•  The local class must be defined before it
is used! This is just like a local variable:
declare before using.

19
Anonymous values
•  In the previous example, we wrote a local class
which was only used once.
•  Usually, if we have some value that we only use
once, we try to avoid naming it. For instance,
we don't write:
int squareX = x * x;
int squareY = y * y;
double hypotenuse = Math.sqrt(squareX + squareY);
System.out.println(hypotenuse);

20
Anonymous values
•  We would usually write:

System.out.println(Math.sqrt((x * x) + (y * y));

•  Here the intermediate values are not stored


anywhere, so cannot be referred to by names.
That's okay because we don't need them again.

21
Anonymous classes
•  Java lets us have anonymous classes too.
•  An anonymous class is a class we will use just
once, "in passing", to create an object.
•  A common thing to use anonymous classes for
is listeners. Let's see how to create an
anonymous ActionListener class.

22
Anonymous class syntax
Here's how to write an anonymous class
and create an object of that class:

new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
… code here
}
}

23
What it means
new ActionListener()
{
class definition
}
creates an object of an anonymous class
–  the anonymous class implements ActionListener
–  the members of the class are contained within the
braces.

24
Another version
new SomeExistingClass()
{
class definition
}
creates an object of an anonymous class
–  the anonymous class extends SomeExistingClass
–  the members of the class are contained within the
braces.

25
Making use of the object
•  Of course, to use the object we've just created,
we need to store it somewhere, or do something
with it.
•  A common pattern is:

button.addActionListener(new ActionListener()
{
// class definition
});

26
Summary: inner classes

•  Inner classes are written inside other


classes.
•  They are (usually) accessed only from
within the outer class.
•  They have access to the other fields and
methods of the outer class.

27
Summary: local classes
•  Local classes are classes within methods
or other code-blocks.
•  They can only be accessed from within
the code-block that contains them.
•  They have access to all the methods and
fields of the class containing the method.
•  They also have access to final local
variables of their containing method.

28
Summary: anonymous classes
•  Anonymous classes are local classes which have
no name and can only be used once, to create an
object.
•  An anonymous class must implement some
interface, or extend some other class. This
interface or class is used in the
new Something() {…}
syntax.
•  Otherwise, they are just like local classes.

29
Exercise

Convert any of your event-handling


programs so that the listeners are inner
classes, local classes, or anonymous
classes, as appropriate.

30

Você também pode gostar