Transcript Session6

Welcome Back!!!
Advanced Java Programming
CSE 7345/5345/ NTU 531
Session 6
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Office Hours:
by appt
3:30pm-4:30pm
SIC 353
Chantale
Laurent-Rice
Welcome Back!!!
[email protected]
[email protected]
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Inheritance
Class A
Class B
Class C
Class D
Class A is the superclass of B
Class B is the subclass of A
Class B is the superclass of C, D, E
Class C, D and E are subclasses of B
Class E
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
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.
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.
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);
}
}
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(ne
w WindowAdapter(){ public void
WindowClosing(WindowEvent e) {
System.exit(0);}
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
});
dframe.show();
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
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.
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.
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.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Example:
Interface
import 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);
}
public void
actionPerformed(ActionEvent
e)
{
String message = new
String("It's showtime!");
if(e.getSource() == button)
{
);
}
}
button.addActionListener(this);
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
textbox.setText(message
}
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...");
}
}
Multiple
Inheritance
class Helicopter extends Aircraft
{
public void heli()
{
);
}
System.out.println("heling..."
}
class Jet extends Aircraft
{
public void jetty()
{
}
...");
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
System.out.println("escaping
Multiple
Inheritance
public 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();
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Class Modifiers
• There are three possible modifiers that
may precede the class keyword.
• Keyword
meaning
abstract
Cannot be instantiated
final
public
Cannot be extended
Can be accessed by any
other class. If this word
is missing, access to the
class is limited to the
current package.
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.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
abstract
class DAbstract
{
String getData();
public void print();
{
System.out.println(getDa
ta());
}
• 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.
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
abstract
abstract MakingItAbstract
{
String getData();
public void print();
{
• Now when you use subclass
MakingItAbstract, You
have to provide an
implementation of getData
System.out.println(getDa
ta());
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Abstract con’t
abstract class MakingItAbstract
{
abstract String getData();
public void print()
{
ta());
}
}
System.out.println(getDa
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();
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
}
Inheritance con’t
Method 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.
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.
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
{
System.out.println("Is bubbling");
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
in the fish class
Example con’t
public 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();
}
}
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.
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();
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Example con’t
public 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
}
}
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.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Example: final
class 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");
}
}
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();//br
eathing
^
2 errors
•
Tool completed with exit code 1
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.
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
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.
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.
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().
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.
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.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
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;
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Example:
Example con’t
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;
}
}
class 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);
}
}
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.
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.
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.
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.
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.
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(){... }
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){…..}
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(){…. }
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.
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
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Example:
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;
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
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(){}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner
Example:
Applet