Advanced Java Programming CSE 7345 / NTU 538N

Download Report

Transcript Advanced Java Programming CSE 7345 / NTU 538N

Welcome Back!!!
Advanced Java Programming
CSE 7345/5345/ NTU 531
Session 5
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
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
In-class Warm-up
• Write a method to reverse a string
without using the reverse method in
the StringBuffer class. The method
signature is as follows:
public static String reverse(String s) {
// Implement it
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Answer
public class InClassNotSoWarm {
public static void main(String[] args) {
System.out.println(reverse("acb"));
}
public static String reverse(String s) {
// Implement it
StringBuffer strBuf = new StringBuffer();
for (int i = s.length() - 1; i >= 0; i--) {
strBuf.append(s.charAt(i));
}
}
}
return strBuf.toString();
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Chapter 8 Class
Inheritance and Interfaces
Objectives

Understand the concept of class inheritance
 
 
 








and the relationship between superclasses and
subclasses.
Create new classes from existing classes.
Learn to use the super keyword.
Learn to use three modifiers: final, protected,
and abstract.
Create abstract classes.
Understand polymorphism and object casting.
Understand the concept of interfaces.
Become familiar with inner classes.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Key Concepts
• The class derived from the
superclass is called the subclass.
• Sometimes a superclass is referred
to as a parent class or a base class,
and a subclass is referred to as a
child class, an extended class, or a
derived class.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Key Concepts
• Subclasses usually have more
functionality than their superclasses.
• The keywords super and this are used
to reference the superclass and the
subclass, respectively.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Key Concepts
• The final modifier is used to prevent
changes to a class, a method, or a
variable.
• A final class cannot be extended.
• A final method cannot be overridden.
• A final variable is a constant.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Key Concepts
• The abstract modifier is used to
design generic superclasses.
• An abstract class cannot be
instantiated.
• An abstract method contains only the
method description without
implementation.
• Its implementation is provided by
subclasses.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
final
• One of the common uses of final is to
create named constants.
• For example, the following application
illustrates this use of final.
• It creates a variable x whose value
cannot be changed.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example: Final
final class V1
{
}
class V2 extends V1
{
}
class FinalClass
{
public static void main(String args[])
{
V1 obj = new V1();
}
}
//Will not compile because cannot inherit from final V1
//class V2 extends V1
// cannot inherit from final V1
//class V2 extends V1 because final cannot be extended
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example: final
class L
{
static final int x = 5;
}
class FinalVariable
{
public static void main(String[] args)
{
System.out.println(L.x);
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Inheritance
• Using inheritance, you can derive one
class, called the derived class or
subclass, from another, called the
base class or superclass.
• The idea here is that you add what
you want to the new class to give it
more customized functionality than
the original class.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Inheritance
• Inheritance is the most crucial concepts in
object-oriented programming, and it has a
very direct effect on how you design and
write your Java classes.
• Inheritance is a powerful mechanism that
means when you write a class you only have
to specify how that class is different from
some other class;
• Inheritance will give you automatic access
to the information contained in that other
class.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Inheritance
• Inheritance is a concept in object-oriented
programming in a strict hierarchy.
• Each class in the hierarchy has
superclasses (classes above it in the
hierarchy) and any number of subclasses (
classes below it in the hierarchy).
• Subclasses inherit attributes and behavior
from their superclasses.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
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
Subclasses
• Inheritance allows one class to reuse the
functionality provided by its superclasses.
• The extends clause in a class declaration
establishes an inheritance relationship between
two classes.
• Syntax:
class clsname2 extends clsname1
{
//class body
}
If the extends clause is omitted from the
declaration of a class, the Java compiler
assumes that Object is its superclass.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example: Inheritance
class X
{
}
class X1 extends X
{
}
class X2 extends X
{
}
class X11 extends X1
{
}
class X12 extends X2
{
}
class X21 extends X2
{
}
class X22 extends X2
{
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example con’t
}
class InheritanceHierarchy
{
public static void main(String[] args)
{
X x;
System.out.println(“Instantiating X “);
x = new X();
System.out.println(“Instantiating X1 “);
x = new X1();
System.out.println(“Instantiating X110 “);
x = new X11();
System.out.println(“Instantiating X12 “);
x = new X12();
System.out.println(“Instantiating X2 “);
x = new X2();
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Answer
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Inheritance
• When a class doesn’t do exactly what
you want, you can build a new class
based on it.
• Your class inherits the original class’s
methods and instance variables, to
which you can add your own code and
data.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Inheritance
• Inheriting classes is a great way to
reuse existing code.
• The term code reuse does not refer
to a text editor’s cut and paste
commands.
• Developing reusable code means
writing and debugging classes, and
then building new classes from them.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Show the output of running
the class Test in the following code lines:
interface A { void print();}
class C {}
class B extends C implements A { public void print() { } }
public class Test {
public static void main(String[] args) {
B b = new B();
if (b instanceof A)
System.out.println("b is an instance of A");
if (b instanceof C)
System.out.println("b is an instance of C");
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
a.
b.
c.
d.
Nothing.
b is an instance
of A.
b is an instance
of C.
b is an instance
of A followed
by b is an
instance of C.
toString() method
• Previous slide answer is D. (b is an instance of A
b is an instance of C)
• Press any key to continue . . .
• The toString() method returns a string equivalent
of the current object.
• Its signature
String toString()
It is common for classes to override this method
so useful information may be provided via the
print() and println() method
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Inheritance
• Inheritance and variables
• The class inherits the state and behavior
defined by all of its superclasses.
• State is determined by variables;
• Behavior is determined by methods.
• Therefore, an object has one copy of every
instance variable defined not only by its
class but also by every superclass of its
class.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Inheritance and Variables
• A static or instance variable in a
subclass may have the same name as a
superclass variable.
• In that case, the variable hides the
superclass variable.
• These two variables may have the
same type or different types.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Inheritance and variables
• The following application demonstrates a
class inheritance hierarchy.
• Class W extends Object and has one instance
variable of type float.
• Class X extends W and has one instance
variable of type StringBuffer.
• Class Y extends X and has one instance
variable of type String.
• Class Z extends Y and has one instance
variable of type Integer.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Inheritance and Variable con’t
• An object of class Z has the instance
variables that are defined in all of
the superclasses.
• The main() method instantiates class
Z with the new operator, initializes
the instance variables, and displays
their values.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example: Inheritance and variables
class W
{
float f;
}
class X extends W
{
StringBuffer sb;
}
class Y extends X
{
String s;
}
class Z extends Y
{
Integer i;
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example: Inheritance and Variables
class Wxyz
{
public static void main(String[] args)
{
Z z = new Z();
z.f = 4.567f;
z.sb = new StringBuffer(“abcde”);
z.s = “ Learning this Inheritance Stuff”;
z.i = new Integer(41);
System.out.println(“z.f = “ + z.f);
System.out.println(“z.sb = “ + z.sb);
System.out.println(“z.s = “ + z.s);
System.out.println(“z.i = “ + z.i);
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Answer
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
What is the output of running the class C.
public class C {
public static void main(String[] args) {
Object[] o = {new A(), new B()};
System.out.print(o[0]);
System.out.print(o[1]);
•
}
}
•
class A extends B {
•
public String toString() {
•
return "A";
•
}
}
class B {
public String toString() {
return "B";
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
a. AB
b. BA
c. AA
d. BB
e. None of above
What is the output of running class C?
class A {
public A() {
System.out.println(
"The default constructor of A is invoked");
}
• a.
}
class B extends A {
public B(String s) {
System.out.println(s);
}
}
none
• b. "The constructor of B is
invoked"
• c. "The default constructor
of A is invoked"
"The constructor of B is
invoked"
• d. "The default constructor
of A is invoked"
public class C {
public static void main(String[] args) {
B b = new B("The constructor of B is invoked");
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Variable Hiding
• Previous slide answer is C.
• Class E declares an instance variable named
x of type int.
• Class F is a subclass of E and also declares
an instance variable named x of type
String
• The main() method first creates an objects
of class F. A reference to this object is
assigned to a local variable named f of
type F.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Variable Hiding
• f.x is, therefore, of type String.
• Next, an object of class E is created.
• A reference to this object is
assigned to a local variable named e
of type E.
• The expression e.x is, therefore, of
type int.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Variable Hiding
• Note:
• The declaration of x in class F hides
the declaration of x in class E.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example: Variable Hiding
• class E
{
int x;
}
class F extends E
{
String x;
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example con’t
class Ef
{
public static void main(String args[])
{
F f = new F();
f.x = “This is a string”;
System.out.println(“f.x = “ + f.x);
E e = new E();
e.x = 45;
System.out.println(“e.x = “ + e.x);
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Answer
f.x = This is a string
e.x = 45
Press any key to continue . . .
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Method Overriding
class A1
{
void hello()
{
System.out.println("hello
from A1");
}
}
class B1 extends A1
{
void hello()
{
System.out.println("hello
from A1");
}
}
class C1 extends B1
{
void hello()
{
System.out.println("Hello from
C1");
}
}
public class MethodOverriding
{
public static void main(String[]
args)
{
C1 obj = new C1();
obj.hello();
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Another Warm-up
Create a class named IntClass as
follows:
public class IntClass {
private int number;
public boolean isEven() {
// Implement it
}
public IntClass(int number) {
// Implement it
}
public boolean isPrime() {
// Implement it
public boolean equals(int
anotherNum) {
// Implement it
}
}
public String toString() {
// Implement it
public static boolean isPrime(int
num) {
// Implement it
}
}
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Answer
public class NotToKool {
public static void main(String[] args) {
IntClass n1 = new IntClass(5);
System.out.println("n1 is even? " + n1.isEven());
System.out.println("n1 is prime? " + n1.isPrime());
System.out.println("5 is prime? " + IntClass.isPrime(15));
}
}
class IntClass {
private int number;
public IntClass(int number) {
this.number = number;
}
public boolean isPrime() {
return isPrime(number);
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Answer con’t
public static boolean isPrime(int num) {
if ((num ==1) || (num ==2)) {
return true;
}
for (int i=2; i<=num/2; i++) {
if (num%i == 0)
return false;
}
return true;
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Answer con’t
public boolean isEven() {
return number%2 == 0;
}
public boolean equals(int anotherNum) {
return number == anotherNum;
}
}
public String toString() {
return number + " ";
}
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
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
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, they have access to the
structure the browser provides: an
existing window, an event-handling and
graphics context, and the surrounding user
interface.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
Example: Java Applet
import java.applet.Applet;
import java.awt.Graphics;
public class FirstApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“This is my first applet!”, 20, 100);
}
}
Compile this code and then enter the following command
appletviewer First Applet.java
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
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.
• Applets also take strong advantage of Java’s
Abstract Windowing Toolkit (AWT), which
provides behavior for creating graphical user
interface (GUI)-based applets 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.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
The keyword “super”
• It is possible to access a hidden
variable by using the super keyword,
as follows:
super.VarName
Here, varName is the name of the
variable in the superclass.
This syntax may be use to read or
write the hidden variable.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil
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
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
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
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
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
5 important Applets methods
• 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
5 important applets methods
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