Nested Classes Nested Classes An nested class is

  • Slides: 72
Download presentation
Nested Classes

Nested Classes

Nested Classes ¨ An nested class is a class that is defined inside another

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 jdk 1. 1

Why use nested classes? ¨ Simplifies many coding tasks – can define small classes

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 jdk 1. 1 ¨ In jdk 1. 0, the clean and simple class

Pre jdk 1. 1 ¨ In jdk 1. 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 –

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

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 x 1; Outer(int x 1){

Simple non-local inner class example class Outer{ private int x 1; Outer(int x 1){ this. x 1 = x 1; } public void foo(){ System. out. println(“fooing”); } public class Inner{ private int x 1 = 0; void foo(){ System. out. println(“Outer value of x 1: “ + Outer. this. x 1); System. out. println(“Inner value of x 1: “ + this. x 1); } }

Simple example, cont -- driver • Rules for instantiation a little funny public class

Simple example, cont -- driver • Rules for instantiation a little funny public class Test. Drive{ 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

Inner class rules ¨ Note that inner class can access outer class instance variables (even private ones). ¨ It does this using the object reference <Outer. Class. Name>. this ¨ Refer to public inner class as <Outer. Class. Name>. <Inner. Class. Name>

When to use non-local inner classes ¨ Most typically used when inner class is

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. ¨

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

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. add. Action. Listener( new Action. Listener(){ public void action. Performed(action.

Anonymous class example but. add. Action. Listener( new Action. Listener(){ public void action. Performed(action. Event ae){ //do work here } } );

Very Basic Applets Programs that run within web browsers

Very Basic Applets Programs that run within web browsers

What are applets? ¨ Applets are simply java programs that run in 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,

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 Web. Start 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

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

Some Hello World Applets ¨ To see how applets work, we start with a couple of versions of a Hello. World 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.

Hello. World. Applet 1 import java. awt. *; import javax. swing. *; public class

Hello. World. Applet 1 import java. awt. *; import javax. swing. *; public class Hello. World. Applet 1 extends JApplet{ public void init(){ get. Content. Pane(). add(new JLabel( “Hello World”, Swing. Constants. CENTER)); } } • Note that all Applets are class that extend either Applet or JApplet • init() is called when the Applet is loaded

Hello. World. Applet 2 import java. awt. *; import javax. swing. *; public class

Hello. World. Applet 2 import java. awt. *; import javax. swing. *; public class Hello. World. Applet 1 extends JApplet{ public void pain. Component(Graphics g){ g. draw. String(“Hello World”, 50); } } • Since Applets are Panels, we can override Paint. Component 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

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, Java 2 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

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

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

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 ¨

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

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

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

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

Part 2 Extending Web Server Functionality Servlets and JSP

Web Servers ¨ A server program that listens on a standard port and handles

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 –

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

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

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

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

Writing servlets ¨ All servlets extend the Servlet class. ¨ All http servlets (by far most typical) should extend the Http. Servlet class. ¨ In extending Http. Servlet, you typically override the following methods: – init, do. Get, do. Post, destroy (very common) – do. Put, do. Delete, do. Options, do. Trace (rare)

Main Http. Servlet Methods ¨ init() – called once when servlet is loaded by

Main Http. Servlet Methods ¨ init() – called once when servlet is loaded by server. Contains any initializations that are common to all requests. ¨ do. Get(Http. Servlet. Request, Http. Servlet. Response) – 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 Http. Servlet Methods, cont. ¨ do. Post(Http. Servlet. Request, Http. Servlet. Response) –

Main Http. Servlet Methods, cont. ¨ do. Post(Http. Servlet. Request, Http. Servlet. Response) – Same as do. Get 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(Http. Servlet. Request, Http. Servlet. Response) is also

Service Method ¨ Important: The method service(Http. Servlet. Request, Http. Servlet. Response) is also called for each servlet invocation. ¨ Service() in turn calls do. Get and do. Post, etc. ¨ It is best not to override service even if you want to handle do. Get and do. Post identically. Simply have one call the other.

Http. Servlet. Request Object ¨ Passed when browser calls do. Get and do. Post.

Http. Servlet. Request Object ¨ Passed when browser calls do. Get and do. Post. ¨ Most import methods for beginning servlet programming – get. Parameter(String param. Name) – get. Parameter. Names() – get. Parameter. Values() ¨ Makes getting data from web pages very simple. ¨ Many other methods for images, cookies, etc.

Http. Servlet. Response Object ¨ Passed when browser calls do. Get or do. Post

Http. Servlet. Response Object ¨ Passed when browser calls do. Get or do. Post ¨ Most import methods for beginning servlet programming: – get. Writer(); • Get Writer for communicating back to client – set. Content. Type(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

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

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

Final Exam Review Questions

Question 0 class A { static void display ( ){ System. out. println (

Question 0 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? ?

Question 1 ¨ 1. 2. 3. 4. 5. Given a class A with a

Question 1 ¨ 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 in the CLASSPATH

Question 2 ¨ 1. 2. 3. 4. 5. Given a class A with a

Question 2 ¨ 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 in the CLASSPATH

Question 3 ¨ List the visibility keywords in order of 1. 2. 3. 4.

Question 3 ¨ List the visibility keywords in order of 1. 2. 3. 4. most to least restrictive. private default protected public protected default private protected default public default private protected

Question 4 ¨ If an iv has private scope in some superclass, then no

Question 4 ¨ If an iv has private scope in some superclass, then no subclass can access the iv using the this pointer.

Question 5 ¨ Immutable classes may contain accessor methods

Question 5 ¨ Immutable classes may contain accessor methods

Question 6 ¨ Immutable classes are Threadsafe.

Question 6 ¨ Immutable classes are Threadsafe.

Question 7 class X{ public boolean equals(Object o){ X an. X = (X) o;

Question 7 class X{ public boolean equals(Object o){ X an. X = (X) o; if (an. X. iv 1 == this. iv 1) return true; return false; } ? int iv 1; ¨ What can be inferred about iv 1? private, protected, default, public, all, some? ?

Question 8 -10 ¨ Assuming the class X is exactly as it appears on

Question 8 -10 ¨ Assuming the class X is exactly as it appears on the previous slide (with public in place of ? ), is the following valid? X x 2 = (X) an. X. 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?

Question 11 ¨ Is it appropriate to store an. X in Hash. Map, again

Question 11 ¨ Is it appropriate to store an. X in Hash. Map, again assuming that X is defined verbatim as you see? ¨ Is it legal to store an. X in a Hash. Map?

Question 12 ¨ Is it possible for a subclass to override a private superclass

Question 12 ¨ Is it possible for a subclass to override a private superclass method?

Question 13 ¨ Can a static variable be used in a non-static context?

Question 13 ¨ Can a static variable be used in a non-static context?

Question 14 ¨ Can a static method access a non-static variable?

Question 14 ¨ Can a static method access a non-static variable?

Question 15 ¨ Can a class with all static methods be instantiated?

Question 15 ¨ Can a class with all static methods be instantiated?

Questions 16 -18 public class Class. A { public void method. One(int i) {

Questions 16 -18 public class Class. A { public void method. One(int i) { } public void method. Two(int i) { } public static void method. Three(int i) { } public static void method. Four(int i) { } } public class Class. B extends Class. A { public static void method. One(int i) { } public void method. Two(int i) { } public void method. Three(int i) { } public static void method. Four(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?

Question 19 -24 Exception handling (T or F) ¨ All java Exceptions must either

Question 19 -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.

Question 25 ¨ Which best describes and Applet? 1. A thin client 2. A

Question 25 ¨ 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

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

Somewhat irritating certification type questions

Question 1) Which of the following lines will compile without warning or error? 1)

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

What will happen if you try to compile and run the following code public class My. Class { 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

Which of the following will compile without error 1) import java. awt. *; package Mypackage; class Myclass {} 2) package My. Package; import java. awt. *; class My. Class{} 3) /*This is a comment */ package My. Package; import java. awt. *; class My. Class{}

What will happen when you compile and run the following code public class My.

What will happen when you compile and run the following code public class My. Class{ 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?

What will be the result of attempting to compile and run the following code? abstract class Mine. Base { abstract void amethod(); static int i; } public class Mine extends Mine. Base { 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) Index. Out. Of. Boundes Error

What will be printed out if you attempt to compile and run the following

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

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 2) not checked in the base class

What will happen if you attempt to compile and run the following code? class

What will happen if you attempt to compile and run the following code? class Base {} class Sub extends Base {} class Sub 2 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? .

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

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