NestedClasses

advertisement
Nested Classes
Nested Classes
 An nested class is a class that is defined
inside another class.
 To this point we have only studied top-level
classes.
– at most one public per file
– arbitrarily many package-scope per file
– either package or public ONLY
 Nested classes introduced in jdk1.1
Why use nested classes?
 Simplifies many coding tasks
– can define small classes on the fly near the
objects created from them + concise syntax
– can access outer classes iv’s automatically – no
need to pass a this pointer to the constructor of
separate outer class
– can be hidden from other classes in the same
package
 However, price to pay in terms of
complexity, number of gotchas, etc.
Pre jdk1.1
 In jdk1.0, the clean and simple class rules were
ballyhooed as a major improvement over C++
 Addition of inner classes complicates things
significantly
 However, they do make certain code much less
awkard to write, particularly when writing GUIs
 Still, you do not have to use them, but they can be
quite cool and I do recommend it in moderation!
Types of nested classes
 Inner classes
– local
• anonymous or named
– non-local
• named only
 Static nested classes
– non-local named only
Non-local inner classes
 Simply a nested class that does not have the static
attribute and is not defined within a class method.
 Can be private, public, package, protected,
abstract, etc. just like any class member.
 Think of outer class as owning inner class – inner
class can only be instantiated via outer class
reference (including this)
 Inner class has access to all outer class iv’s,
private or otherwise!
Simple non-local inner class
example
class Outer{
private int x1;
Outer(int x1){
this.x1 = x1;
}
public void foo(){ System.out.println(“fooing”);}
public class Inner{
private int x1 = 0;
void foo(){
System.out.println(“Outer value of x1: “ + Outer.this.x1);
System.out.println(“Inner value of x1: “ + this.x1);
}
}
Simple example, cont -- driver
• Rules for instantiation a little funny
public class TestDrive{
public static void main(String[] args){
Outer outer = new Outer(); // can create in regular way
Inner inner = outer.new Inner(); //must call new through
//outer object handle
inner.foo();
// note that this can only be done if inner is visible
// according to the regular scoping rules
}
}
Inner class rules
 Note that inner class can access outer class
instance variables (even private ones).
 It does this using the object reference
<OuterClassName>.this
 Refer to public inner class as
<OuterClassName>.<InnerClassName>
When to use non-local inner
classes
 Most typically used when inner class is
instantiated from outer class.
 If classes naturally “belong together”, it is
cumbersome to pass a this pointer to a
separate outer class just so second class can
access first class’s properties/methods.
 Note that inner class can access outer class’s
private data, making them even more
powerful than mechanism implied above!
Local inner classes
 Inner classes may also be defined within class
methods.
 These are called local inner classes.
 Principle advantage is scoping: such classes are
completely inaccessible anywhere but the method
itself where they are defined.
 Thus, they have no visibility attribute (public, etc.)
 Also, can NOT access local variables other than
those declared with final attribute.
Local anonymous inner classes
 Local inner classes can be taken a step
further – it is not required to give them an
explicit name.
 This is very convenient when you want to
use a class only once and the code that it
contains is succinct.
 Great example is defining Swing callback
functions.
Anonymous class example
but.addActionListener(
new ActionListener(){
public void actionPerformed(actionEvent ae){
//do work here
}
}
);
Very Basic Applets
Programs that run within web
browsers
What are applets?
 Applets are simply java programs that run in web
browsers.
 Created a big stir in mid-90’s when Netscape
agreed to embed jvm in Navigator web browswer.
 Great promise – applications automatically
distributed to anyone on any platform!
 Reality – non-uniform browswer support,
limitations imposed by security, easier ways to
accomplish same thing!
What are applets, cont.
 Still useful in just the right situation
– fancy, full-fledged client
– can make some assumptions/have some control over
client technology
 Also, very good for understanding issues in web
client-server programming
 Otherwise, server-heavy programming with html
or client-side scripting wins out.
 Also, Java WebStart new alternative
– can launch full applications remotely without need for
host browser
Applet inheritance tree
Object
Component
Container
Window
Panel
Frame
Applet
JFrame
JApplet
Use to access
Swing Components
Some Hello World Applets
 To see how applets work, we start with a
couple of versions of a HelloWorld program
– One uses the fact that an Applet is a Panel with
a graphics object
– The other uses a button label
 Soon, we will add full event-handling
capabilities and nice graphics. This is just a
start.
HelloWorldApplet1
import java.awt.*;
import javax.swing.*;
public class HelloWorldApplet1 extends JApplet{
public void init(){
getContentPane().add(new JLabel(
“Hello World”,
SwingConstants.CENTER));
}
}
• Note that all Applets are class that extend either
Applet or JApplet
• init() is called when the Applet is loaded
HelloWorldApplet2
import java.awt.*;
import javax.swing.*;
public class HelloWorldApplet1 extends JApplet{
public void painComponent(Graphics g){
g.drawString(“Hello World”, 50, 50);
}
}
• Since Applets are Panels, we can override PaintComponent
and get a Graphics Object
• This will become particularly handy when doing animations
Running Applets
 To run applets, do the following:
– Compile class file in regular way
– Create an html file that includes an applet tag pointing
to the applet
<applet code = “Appletname.class” width = 200 height =
50></applet> (width and height are pixel coords)
– Invoke browser or appletviewer on html file
 Note that applet tag can include other parameters,
some of which of used by browser automatically
(e.g. width).
 Also, Java2 plug-in required for browsers to
support applets. Good to test with appletviewer
first.
Life Cycle of Applet
 To write more sophisticated applets, a
number of other methods may need to be
overwritten.
–
–
–
–
void init()
void start()
void stop()
void destroy()
 We discuss the role of each next.
init() method
 The browswer calls the init method when the
applet is loaded for the first time.
 init() behaves much like a constructor.
 Typical uses:
–
–
–
–
parsing param values from html files
opening streams and sockets
creating GUI components
opening database connections
 Important: note that the refresh button doesn’t
necessarily reload applet. This is browserdependent. To guarantee reloading, browser needs
to be killed and restarted.
start() method
 called every time page is located
– this can mean moving off and back onto page, hitting
reload, etc.
 always called after init() when page is first loaded.
 Typical uses:
– starting animations
– anything else that needs to start anew with every
location of applet
– for simpler things this method can be ignored
stop() method
 called whenever user moves off the page
where applet sits
 always called after start
 typical uses
– ending animations
– stopping other time-consuming system activity
 often ignore this for simpler applets
destroy() method
 called once when browser shuts down
normally
 always called after stop()
 typical uses:
– close database connections
– close streams
– clean up any other resources
 often ignored for simpler applets
More on applet life-cycle
 It’s very import to be aware that some other
software, ie the host browser, is calling these
methods at certain times.
 You the program do not call these methods.
 This is classic OO framework: “don’t call us, we’ll
call you”.
 You write the class and specialize certain methods,
some other code calls your custorm versions of
those methods at specified times.
Other applet issues
 Security
– Horstmann pg. 499
 Pop-up windows
– Horstmann pg. 500
 Applet tags and attributes
– Horstmann pg. 502
 Passing info to applets
– Horstmann pg. 506
 Applets making socket connections
Part 2
Extending Web Server Functionality
Servlets and JSP
Web Servers
 A server program that listens on a standard port
and handles http protocol.
 Http protocol consists mainly of requests for
documents
 Documents are typically html files
 Two most important http protocol elements:
– GET (request document, may upload data)
– POST (request document, upload data).
 This protocol is hidden from you by browser.
Early Web Servers
 Earliest web sites were static:
– Browser requests page
– Server hands over page
 CGI (Common Gateway Interface) scripts defined
a standard for extending functionality
– http GET/POST data could be passed to and processed
in separate function (C, Perl, Python, etc.)
– This often included call to back-end database and
response to user via modified html document
Shortcomings of CGI
 E-Commerce became more popular and
web sites became more heavily used. This
brought to the fore some shortcomings of
CGI:
– New process spawned for every hit – not
scalable
– No concept of sesssion or state
– Pretty low level
– Security risks (C in particular)
Servlets
 Java’s answer to CGI, very simple, high-
level
 Requirements: a servlet-enabled web server
 When specified by your web page, web
page passes http requests to java method
(assuming everything is setup properly)
 Servlet method then has access to all of
Java capabilities – jdbc very important here.
 Servlet then writes html back to user.
Servlets, cont.
 Important: a web server takes care of all
interactions with the servlet – servlet
extends functionality.
 On the client side, servlet pages are
typically requested in one of two ways:
– As a regular URL address
– As a link in a regular html document
 Details are server-dependent
Writing servlets
 All servlets extend the Servlet class.
 All http servlets (by far most typical) should
extend the HttpServlet class.
 In extending HttpServlet, you typically
override the following methods:
– init, doGet,doPost, destroy (very common)
– doPut, doDelete, doOptions, doTrace (rare)
Main HttpServlet Methods
 init()
– called once when servlet is loaded by server.
Contains any initializations that are common to
all requests.
 doGet(HttpServletRequest,
HttpServletResponse)
– Called each time the servlet receives an http
GET request posted by a client. Passes two
objects, one representing the information of the
request, the other used to configure a response.
Main HttpServlet Methods, cont.
 doPost(HttpServletRequest,
HttpServletResponse)
– Same as doGet but for an http POST request.
 destroy()
– Called before servlet is unloaded from memory.
Performs any final cleanup, freeing memory,
closing connections, etc.
Service Method
 Important: The method
service(HttpServletRequest,
HttpServletResponse)
is also called for each servlet invocation.
 Service() in turn calls doGet and doPost,
etc.
 It is best not to override service even if you
want to handle doGet and doPost
identically. Simply have one call the other.
HttpServletRequest Object
 Passed when browser calls doGet and doPost.
 Most import methods for beginning servlet
programming
– getParameter(String paramName)
– getParameterNames()
– getParameterValues()
 Makes getting data from web pages very simple.
 Many other methods for images, cookies, etc.
HttpServletResponse Object
 Passed when browser calls doGet or doPost
 Most import methods for beginning servlet
programming:
– getWriter();
• Get Writer for communicating back to client
– setContentType(String);
• Typically use “text/html”, indicating that html will
be sent back to the browser
Examples
 Use html form to connect to servlet, accept
form data, and then echo it back with the
output stream.
 Postdata.java
: Java servlet
 Form.html
: HTML front-end
 Basic steps very simple – just need to
know a little HTML and a few Java
methods
General Comments
 Recall that each request for a servlet gets its
own thread but access the same methods.
Thus, synchronization issues arise.
Final Exam Review
Questions
Question0
class A {
static void display ( ){ System.out.println ( "Class A" ) ; }
}
class B extends A {
static void display ( ) { System.out.println ( "Class B" ); }
}
When we create an object and call the display ( ) method as:.
A aa = new B() ;
aa.display ( )
What is displayed ??
What if display is non-static??
Question1

1.
2.
3.
4.
5.
Given a class A with a protected iv ivp, which of
the following are possible ways of accessing
ivp?
using the this pointer within a subclass of A
within the same package
using the this pointer within a subclass of B
outside of the package
using an instance of A from within any class in
the same package
using an instance of A from within any class
using an instance of A from within any class in
the CLASSPATH
Question2

1.
2.
3.
4.
5.
Given a class A with a private iv ivp, which of
the following are possible ways of accessing
ivp?
using the this pointer within a subclass of A
within the same package
using the this pointer within a subclass of B
outside of the package
using an instance of A from within any class in
the same package
using an instance of A from within any class
using an instance of A from within any class in
the CLASSPATH
Question3
 List the visibility keywords in order of
1.
2.
3.
4.
most to least restrictive.
private default protected public
public protected default private
private protected default public
public default private protected
Question4
 If an iv has private scope in some
superclass, then no subclass can access the
iv using the this pointer.
Question5
 Immutable classes may contain accessor
methods
Question6
 Immutable classes are Threadsafe.
Question7
class X{
public boolean equals(Object o){
X anX = (X) o;
if (anX.iv1 == this.iv1) return true;
return false;
}
? int iv1;
 What can be inferred about iv1?
private, protected, default, public, all, some??
Question8-10
 Assuming the class X is exactly as it
appears on the previous slide (with public in
place of ?), is the following valid?
X x2 = (X) anX.clone();
 If so, is this clone and adequate clone? If
not, how would you modify the class X to
make it cloneable?
 Is X serializable as-is?
Question11
 Is it appropriate to store anX in HashMap,
again assuming that X is defined verbatim
as you see?
 Is it legal to store anX in a HashMap?
Question12
 Is it possible for a subclass to override a
private superclass method?
Question13
 Can a static variable be used in a non-static
context?
Question14
 Can a static method access a non-static
variable?
Question15
 Can a class with all static methods be
instantiated?
Questions16-18
public class ClassA {
public void methodOne(int i) { }
public void methodTwo(int i) { }
public static void methodThree(int i) { }
public static void methodFour(int i) { } }
public class ClassB extends ClassA {
public static void methodOne(int i) { }
public void methodTwo(int i) { }
public void methodThree(int i) { }
public static void methodFour(int i) { } }
a. Which method overrides a method in the superclass?
b. Which method hides a method in the superclass?
c. What do the other methods do?
Question19-24 Exception
handling (T or F)
 All java Exceptions must either be caught or
thrown.
 Classes can throw Exceptions.
 Static methods can throw Exceptions.
 main can be declared to throw Exception
 rethrowing Exceptions is bad programming style
 Every method that throws an Exception should be
placed in its own try-catch block
 It is bad programming style to have empty catch
blocks, at least in production code.
Question25
 Which best describes and Applet?
1. A thin client
2. A fat client
3. A lightweight web server
4. A full-blown application server
Question 26-31
 All applets extend either Applet or JApplet.
 Applets need a main method to run
 All applets must override at least the start, stop,
init, and destroy methods.
 start, stop, init, and destroy methods are declared
abstract in the Applet class
 Unsigned applets cannot make socket connections
to any server.
 Unsigned applets cannot access files on the local
directory
Somewhat irritating
certification type questions
Question 1)
Which of the following lines will compile without
warning or error?
1) float f=1.3;
2) char c="a";
3) byte b=257;
4) boolean b=null;
5) int i=10;
What will happen if you try to compile and
run the following code
public class MyClass {
public static void main(String arguments[]) {
amethod(arguments);
}
public void amethod(String[] arguments) {
System.out.println(arguments);
System.out.println(arguments[1]);
}}
1) error Can't make static reference to void amethod.
2) error method main not correct
3) error array must include parameter
4) amethod must be declared with String
Which of the following will compile without error
1)
import java.awt.*;
package Mypackage;
class Myclass {}
2)
package MyPackage;
import java.awt.*;
class MyClass{}
3)
/*This is a comment */
package MyPackage;
import java.awt.*;
class MyClass{}
What will happen when you compile and run the following code
public class MyClass{
static int i;
public static void main(String argv[]){
System.out.println(i);
}}
1) Error Variable i may not have been initialized
2) null
3) 1
4) 0
What will be the result of attempting to compile and run the
following code?
abstract class MineBase {
abstract void amethod();
static int i;
}
public class Mine extends MineBase {
public static void main(String argv[]){
int[] ar=new int[5];
for(i=0;i < ar.length;i++)
System.out.println(ar[i]);
}}
1) a sequence of 5 0's will be printed
2) Error: ar is used before it is initialized
3) Error Mine must be declared abstract
4) IndexOutOfBoundes Error
What will be printed out if you attempt to compile and run the following cod
int i=1;
switch (i) {
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
default:
System.out.println("default");
}
1) one
2) one, default
3) one, two, default
Which of the following statements are true?
1) Methods cannot be overriden to be more private
2) Static methods cannot be overloaded
3) Private methods cannot be overloaded
4) An overloaded method cannot throw exceptions
not checked in the base class
What will happen if you attempt to compile and run the
following code?
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b;
}}
1) Compile and run without error
2) Compile time Exception
3) Runtime Exception
What will happen when you attempt to compile and run the following code?.
class Background implements Runnable{
int i=0;
public int run(){
while(true){
i++;
System.out.println("i="+i);
} //End while
return 1;
}//End run
}//End class
1) It will compile and the run method will print out the increasing value of i.
2) It will compile and calling start will print out the increasing value of i.
3) The code will cause an error at compile time.
4) Compilation will cause an error because while cannot take
What will be the result when you try to compile and run the following code?
private class Base{
Base(){
int i = 100;
System.out.println(i);}}
public class Pri extends Base{
static int i = 200;
public static void main(String argv[]){
Pri p = new Pri();
System.out.println(i);}}
1) Error at compile time
2) 200
3) 100 followed by 200
4) 100
Download