advanced java programming cse 7345/5345/ ntu 531

51
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner Advanced Java Programming CSE 7345/5345/ NTU 531 Session 6 Welcome Welcome Back!!! Back!!!

Upload: stew

Post on 19-Jan-2016

35 views

Category:

Documents


0 download

DESCRIPTION

Welcome Back!!!. Advanced Java Programming CSE 7345/5345/ NTU 531. Session 6. Office Hours: by appt 3:30pm-4:30pm SIC 353. Chantale Laurent-Rice. Welcome Back!!!. [email protected]. [email protected]. Inheritance. Class A. Class A is the superclass of B - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Advanced Java Programming

CSE 7345/5345/ NTU 531Session 6

Welcome Welcome Back!!!Back!!!

Page 2: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

[email protected]@engr.smu.edu

Chantale Laurent-

Rice

Welcome Welcome Back!!!Back!!!

[email protected]@aol.com

Office Hours:by appt3:30pm-4:30pmSIC 353

Page 3: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Inheritance

Class A

Class B

Class C Class D Class E

Class A is the superclass of BClass B is the subclass of AClass B is the superclass of C, D, EClass C, D and E are subclasses of B

Page 4: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Why Inheritance?

• Using inheritance allows you to base your classes on other classes, reusing code and adding to it

• Allows you to use or redefine the members of the superclass as you like, customizing that class for your own use

Page 5: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Why Inheritance? con’t..

• In fact, you can create classes that must be treated as superclasses.

• These classes are called abstract classes

• An abstract class cannot be instantiated directly into an object; you must instead derive a new class from it first, overriding those members that are specifically declared abstract.

Page 6: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Why inheritance?

• Java is truly an OOP, and it relies on inheritance a great deal.

• The developers at Sun Microsystems have created huge packages – class libraries – full of classes that you can use as superclasses.

• This is important if, for example you want to create an applet in Java.

Page 7: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Applet from the java.Applet package’s class

import java.applet.Applet;import java.awt.*;

public class applet extends Applet{ public void paint(Graphics g) {

g.drawString("this creates a superclass based on the Applet class " + "using the extends keyword ", 20, 50);

}}

Page 8: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Applet from the java.awt.frame

import java.awt.*;import java.awt.event.*;

class AppletFrame extends Frame

{ public void paint(Graphics g) {

g.drawString("this creates a windowed application and" +"basing the window, itself on the java.awt.Frame class ", 20, 50);

}}

public class Application1{

public static void main(String[] args){

AppletFrame dframe = new AppletFrame();

dframe.setSize(800, 200);

dframe.addWindowListener(new WindowAdapter(){ public void WindowClosing(WindowEvent e) { System.exit(0);}

});dframe.show();

}

}

Page 9: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Why interfaces?

• An interface is a list of method that define some kind of behavior

• And are provided without implementation

• A class may implement many interfaces

Page 10: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Why interfaces? con’t

• Suppose you want to create an Applet that handles button clicks.

• To create a standard applet, you can derive a class from the java.applet.Applet class, and to handle button clicks, you use another class, named ActionListener.

Page 11: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Why interfaces? con’t

• Therefore, it looks as though you’ll have to base your applet on both the Applet and the ActionListener classes.

• However, basing a subclass on two or more superclasses is called multiple inheritance, and it turns out that Java doesn’t support multiple inheritance (C++ do).

• In practice, this means you can only use the extends keyword with one class.

Page 12: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Why interfaces? con’t

• To solve this problem, Java implements classes such as ActionListener as interfaces.

• That means you can extend your applet from the Applet class and use the implements keyword to add the button-click handling.

Page 13: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example:Interfaceimport java.applet.Applet;

import java.awt.*;import java.awt.event.*;

public class ClickerInterface extends Applet implements ActionListener

{

TextField textbox;Button button;

public void init(){

textbox = new TextField(20);

add(textbox);button = new

Button("Click Here!");add(button);

button.addActionListener(this);}

public void actionPerformed(ActionEvent e){ String message = new String("It's showtime!"); if(e.getSource() == button) { textbox.setText(message); } }

}

Page 14: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Multiple Inheritance

class Vehicle{

public void start(){

System.out.println("Starting...");}

}class Car extends Vehicle{

public void drive(){ System.out.println("driving..."); }

}class Aircraft extends Vehicle{

public void fly(){ System.out.println("I am flying..."); }

}

class Helicopter extends Aircraft{

public void heli(){ System.out.println("heling..."); }

}class Jet extends Aircraft{

public void jetty(){ System.out.println("escaping..."); }

}

Page 15: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Multiple Inheritancepublic class DVehicle

{public static void main(String[] args){

System.out.println("Creating an multilevel Inheritance... ");Car DCar = new Car();DCar.start();DCar.drive();DCar.fly();

System.out.println();System.out.println("Creating another inheritance level ");

Jet DJet = new Jet();DJet.start();DJet.fly();DJet.jetty();

}}

Page 16: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Class Modifiers

• There are three possible modifiers that may precede the class keyword.

• Keyword meaningabstract Cannot be instantiated

final Cannot be extendedpublic Can be accessed by any

other class. If this word is missing, access to the class is limited to the

current package.

Page 17: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

abstract• Abstract classes are very important in

object-oriented programming.• In some cases, writing classes can

provide general code. It’s up to the developer who subclasses your class to customize it.

• To make sure the developer customizes your code, you can make the method abstract, which means the developer will have to override your method; otherwise Java will complain.

Page 18: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

abstract

class DAbstract{

String getData();public void print();{

System.out.println(getData());

}

}

• Note there’s no implementation of the getData() method because I want the developers to specify what data they want to print out.

• To make sure that they know that they must provide an implementation of the getData method, I must make the method abstract.

Page 19: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

abstract

abstract MakingItAbstract{

String getData();public void print();{

System.out.println(getData());

}

}

• Now when you use subclass MakingItAbstract, You have to provide an implementation of getData

Page 20: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Abstract con’tabstract class MakingItAbstract{

abstract String getData();

public void print(){

System.out.println(getData());

}

}

class Ex extends MakingItAbstract{

String getData(){

return "Hello I am implementing the getData()";

}

}public class PuttingSubclasstoWork{

public static void main(String[] args){

System.out.println("Putting the subclass to work");

Ex DEx = new Ex();

DEx.print();

}}

Page 21: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Inheritance con’tMethod Overriding

• Method Overriding occurs when a class declares a method that has the same type signature as a method declared by one of its superclasses.

• When a method in a subclass overrides a method in a superclass, the method in the superclass is hidden relative to the subclass object.

Page 22: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Method Overriding

• Method overriding is a very important capability because it forms the basis for run-time polymorphism.

• Polymorphism means “One interface, multiple implementations.”

• The signature of the method defines the interface, and each overridden version provides a unique implementation.

Page 23: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example: method overridden

class animal{

public void breathe(){

System.out.println("Is Breathing");}

}class fish extends animal{

public void breathe() //overriding the breathe method in the fish class

{System.out.println("Is bubbling");

}}

Page 24: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example con’tpublic class Overriding{

public static void main(String[] args){

System.out.println("Creating an animal... ");animal DAnimal = new animal();DAnimal.breathe();

System.out.println();System.out.println("Creating fish");fish DFish = new fish();DFish.breathe();

}}

Page 25: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

The keyword “super”

• It is possible to access overriding members by using the super keyword

• Super much like this keyword except that super doesn’t refer in the current object but rather to its superclass.

Page 26: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example: Keyword “super”

class animal2{

public void breathe(){

System.out.println("Is Breathing");}

}class fish extends animal2{

public void breathe() //overriding the breathe method in the fish class{

System.out.println("Is bubbling");}public void newBreathe(){

super.breathe();}

}

Page 27: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example con’tpublic class AccessingWithSuper{

public static void main(String[] args){

System.out.println("Creating an animal... ");animal DAnimal = new animal();DAnimal.breathe();

System.out.println();System.out.println("Creating fish");fish SuperFish = new fish();SuperFish.newBreathe();// breathing

}}

Page 28: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Final class

• The final class cannot be extended.• Classes are sometimes declared in

this manner so the methods implemented by that class cannot be overridden.

• For example, the Math class is final.• If a class is final, all of its methods

are also final.

Page 29: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example: finalclass animal3{

public void breathe(){

System.out.println("Is Breathing");}

}class fish extends animal3{

public void breathe() //overriding the breathe method in the fish class{

System.out.println("Is bubbling");}

}

Page 30: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Answer….error• From Animal3()• C:\animal3.java:8: cannot

inherit from final animal3• class fish extends animal3• ^• 1 error

• Tool completed with exit code 1

• From Main()• .\animal3.java:8: cannot inherit

from final animal3• class fish extends animal3• ^• C:\OverridingFinal.java:13:

cannot resolve symbol• symbol : method newBreathe

()• location: class fish•

OverFish.newBreathe();//breathing

• ^• 2 errors

• Tool completed with exit code 1

Page 31: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Inheritance and methods

• The previous section described how method overriding operates in an inheritance hierarchy.

• The dynamic dispatch mechanism in Java automatically selects the correct version for execution based upon the type of objects being referred to at the time the method is executed.

Page 32: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Inheritance and methods

• Thus, an overriding method masks the one defined by the superclass. But this raises an interesting question:

• What if you want to access the functionality present in the superclass version of an overridden method?

• To access a superclass method use the super keyword

Page 33: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Inheritance and constructors

• The state and behavior of a class are defined not only by that class but also by each of its superclasses.

• Therefore, in order to correctly initialize an object, it is not sufficient to execute a constructor only for one class.

• A constructor for each superclass must also be executed.

Page 34: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Inheritance and constructors

• Furthermore, a superclass constructor must execute before a subclass constructor.

• This is necessary so the state and behavior defined by the superclass may be correctly and completely initialized before the subclass constructor executes.

Page 35: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

“super” vs. “this”

• The super keyword is used to explicitly invoke a superclass constructor.

• The this keyword is used for a constructor to invoke another constructor in the same class.

• If you use this form, it must appear as the first statement of the constructor.

• Therefore, a given constructor cannot use both super() and this().

Page 36: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

“super” vs. “this”

• However, if you write a constructor that does not use either super() or this() to explicitly invoke another constructor, the Java compiler automatically calls super() to invoke the default superclass constructor.

• Recall that a default constructor has no arguments.

Page 37: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

“super” vs., “this”

• In other words, the Java compiler assumes that the first line of every constructor is an implicit call to the default superclass constructor unless you explicitly use super() or this() to request different behavior.

Page 38: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example:class S1{

int s1;S1(){

System.out.println(“S1 Constructor”); s1 =1;

}}class T1 extends S1{

int t1;T1(){

System.out.println(“T1 Constructor”); t1 = 2;

}}

Page 39: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example con’tclass U1 extends T1{

int u1;U1(){

System.out.println("U1 Constructor");

u1 = 3;}

}class InheritanceAndConstructors1{

public static void main(String[] args){

U1 u1 = new U1(); System.out.println("u1.s1

= " + u1.s1);System.out.println("u1.t1

= " + u1.t1);

System.out.println("u1.u1 = " + u1.u1);}

}

class S1{

int s1;S1(){

System.out.println("S1 Constructor");

s1 =1;}

}class T1 extends S1{

int t1;T1(){

System.out.println("T1 Constructor");

t1 = 2;}

}

Page 40: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Chapt 10 Applets

• How applets and Applications Are Different?

• Java applications are standalone Java programs that can be run by using just the Java interpreter.

• Java applets, however, are from inside a WWW browser.

Page 41: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Creating applets

• To create an applet, you create a subclass of the class Applet.

• The applet class, part of the java.applet package provides much of the behavior your applet needs to work inside a java-enabled browser.

Page 42: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Creating applets con’t

• Applets also take strong advantage of Java’s Abstract Windowing Toolkit and applications: drawing to the screen: creating windows, menu bars, buttons, check boxes, and other UI elements; and managing user input such as mouse clicks and keypresses.

• The AWT classes are part of the java.awt.package.

Page 43: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Major applet activities• To create a basic Java application,

your class has to have one method, main() method, with a specific signature.

• Then, when your application runs, main() is found and executed, and from main() you can set up the behavior that your program needs to run.

Page 44: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Creating applets con’t

• Applets are similar but more complicated - and in facts, applets don’t need a main() method at all.

• Applets have many different activities that correspond to various major events in the life cycle of the applet.

For example, initialization, painting, and mouse events.Each activities has a corresponding method, so when an event occurs, the browser or other Java-enabled tool calls those specific methods.

Page 45: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

5 important Applets methods

Initialization- occurs when the applet is first loaded or reloaded, similar to the main() method.

public void init(){... }

Starting- start the applet (can happen many different times during an applet’s lifetime.

public void start(){... }

Page 46: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

5 important Applets methods con’t

• Painting- is the way the applet actually draws something on the screen, be it text, a line, a colored background, or an image.– public void paint(Graphics g){…..}

Page 47: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

5 important applets methods con’t

Stopping- goes hand in hand with starting. Stopping occurs when the reader leaves the page that contains a currently running applet, or you can stop the applet yourself by calling stop().

public void stop(){….}

• Destroying- enables the applet to clean up after itself just before it is freed or the browser exits.– public void destroy(){…. }

Page 48: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

The life cycle of an applet

• They are defined by the java.applet.Applet class and, therefore, are inherited by every applet.

• init()- is called only when the applet begins execution.

• start()- is executed after the init() method completes execution.

• stop()- is invoke when the applet viewer is minimized and start() is called when the applet viewer is later maximized.

• destroy()- is called by the applet viewer or Web browser before the applet is terminated.

Page 49: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Applet and its superclasses

Java.lang.Object

Java.awt.Component

Java.awt.Container

Java.awt.Panel

Java.applet.Applet

Page 50: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example:

Applet import java.awt.event.*;import java.applet.*;import java.awt.*;

/* <APPLET CODE=Password2.class WIDTH=300 HEIGHT=300></APPLET>*/

public class Password2 extends Applet implements ActionListener{

public TextField text1;public TextField text2;

Page 51: Advanced Java Programming CSE 7345/5345/ NTU 531

Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner

Example: Applet

public void init(){

text1 = new TextField(30);add(text1);text2 = new TextField(30);add(text2);

text1.setEchoChar('*');text1.addActionListener(this);

}

public void actionPerformed(ActionEvent e){

if(e.getSource() == text1){

text2.setText(text1.getText());}

}

public void start(){}

public void stop(){}

}