0% found this document useful (0 votes)
33 views37 pages

Method Overriding in Polymorphism

Uploaded by

zunairatariq985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views37 pages

Method Overriding in Polymorphism

Uploaded by

zunairatariq985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Polymorphism

Polymorphism

Inheritance and Reuse of code:


every time a new sub-class is defined, programmers are reusing the code in a super-class.
All non-private members of a super-class are inherited by its sub-class:
1) an attribute in a super-class is inherited as-such in a sub-class
2) a method in a super-class is inherited in a sub-class:
a) as-such, or
b) is substituted with the method which has the same name and parameters (overriding) but a different implementation
Definition
Polymorphism is one of three pillars of object-orientation.
Polymorphism:
many different (poly) forms of objects that share a common interface respond differently when a method of that
interface is invoked:
1) a super-class defines the common interface
2) sub-classes have to follow this interface (inheritance), but are also permitted to provide their own implementations
(overriding)
A sub-class provides a specialized behaviors relying on the common elements defined by its super-class.
Behavior :
Suppose we have a hierarchy of classes:
1) The top class in the hierarchy represents a common interface to all classes below. This class is the base class.
2) All classes below the base represent a number of forms of objects, all referred to by a variable of the base class type.
What happens when a method is invoked using the base class reference?
The object responds in accordance with its true type.
What if the user pointed to a different form of object using the same
reference? The user would observe different behavior.
This is polymorphism.
Method Overriding
When a method of a sub-class has the same name and type as a method of the super-class, we say that this method is
overridden.
When an overridden method is called from within the sub-class:
1) it will always refer to the sub-class method
2) super-class method is hidden
Example: Hiding with Overriding
class A {
int i, j;
A(int a, int b) {
i = a; j = b;
}
void show() {
[Link]("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
[Link]("k: " + k);
}
}
When show() is invoked on an object of type B, the version of show()
defined in B is used:
class Override {

1|Page
Polymorphism

public static void main(String args[]) {


B subOb = new B(1, 2, 3);
[Link]();
}
}
The version of show() in A is hidden through overriding
Super and Method Overriding
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
[Link]();
[Link]("k: " + k);
}
}
The super-class version of show() is called within the sub-class’s version.
Overriding versus Overloading 1
Method overriding occurs only when the names and types of the two methods (super-class and sub-class methods) are
identical. If not identical, the two methods are simply overloaded:
class A {
int i, j;
A(int a, int b) {
i = a; j = b;
}
void show() {
[Link]("i and j: " + i + " " + j);
}
}
The show() method in B takes a String parameter, while the show()
method in A takes no parameters:
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b); k = c;
}
void show(String msg) {
[Link](msg + k);
}
}
The two invocations of show() are resolved through the number of
arguments (zero versus one):
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
[Link]("This is k: ");
[Link]();
}
}
Dynamic Method Invocation
Overriding is a lot more than the namespace convention. Overriding is the basis for dynamic method dispatch – a call to
an overridden method is resolved at run-time, rather than compile-time. Method overriding allows for dynamic method
invocation:
1) an overridden method is called through the super-class variable
2) Java determines which version of that method to execute based on the type of the referred object at the time the call
occurs
3) when different types of objects are referred, different versions of the overridden method will be called.
Example: Dynamic Invocation 1
2|Page
Polymorphism

A super-class A:
class A {
void callme() {
[Link]("Inside A's callme method");
}
}
Two sub-classes B and C:
class B extends A {
void callme() {
[Link]("Inside B's callme method");
}
}
class C extends A {
void callme() {
[Link]("Inside C's callme method");
}
}
B and C override the A’s callme() method.
Overridden method is invoked through the variable of the super-class type. Each time, the version of the callme() method
executed depends on the type of the object being referred to at the time of the call:
class Dispatch {
public static void main(String args[]) {
A a = new A();
B.b = new B();
C.c = new C();
A r;
r = a; [Link]();
r = b; [Link]();
r = c; [Link]();
}
}
Polymorphism Again
One interface, many behaviors:
1) super-class defines common methods for sub-classes
2) sub-class provides specific implementations for some of the
methods of the super-class
A combination of inheritance and overriding – sub-classes retain flexibility to define their own methods, yet they still
have to follow a consistent interface.
Example: Polymorphism 1
A class that stores the dimensions of various 2-dimensional objects:
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a; dim2 = b;
}
double area() {
[Link]("Area is undefined.");
return 0;
}
}
Rectangle is a sub-class of Figure:
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
double area() {
[Link]("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
3|Page
Polymorphism

Triangle is a sub-class of Figure:


class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
double area() {
[Link]("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
Invoked through the Figure variable and overridden in their respective subclasses, the area() method returns the area of
the invoking object:
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r; [Link]([Link]());
figref = t; [Link]([Link]());
figref = f; [Link]([Link]());
}
}

Own Exception Handling


Default exception handling is basically useful for debugging.
Normally, we want to handle exceptions ourselves because:
1) if we detected the error, we can try to fix it
2) we prevent the program from automatically terminating
Exception handling is done through the try and catch block
Try and catch:
1) try surrounds any code we want to monitor for exceptions
2) catch specifies which exception we want to handle and how.
When an exception is thrown in the try block:
try {
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
}
catch (ArithmeticException e) {
[Link]("Division by zero.");
}
The exception is handled and the execution [Link] scope of catch is restricted to the immediately
preceding try statement - it cannot catch exceptions thrown by another try statements
try { … }
catch (ArithmeticException e) { … }
[Link]("After catch statement.");
Not with the next statement after a = 42/d; which caused the exception!
a = 42 / d;
[Link]("This will not be printed.");
Catch and Continue 1
The purpose of catch should be to resolve the exception and then continue as if the error had never happened.
Try/catch block inside a loop:
import [Link];
class HandleError {
public static void main(String args[]) {

4|Page
Own Exception Handling

int a=0, b=0, c=0;


Random r = new Random();
After exception-handling, the program continues with the next iteration:
for (int i=0; i<32000; i++) {
try {
b = [Link]();
c = [Link]();
a = 12345 / (b/c);
} catch (ArithmeticException e) {
[Link]("Division by zero.");
a = 0; // set a to zero and continue
}
[Link]("a: " + a);
}
}
}
Exception Display
All exception classes inherit from the Throwable class. Throwable overrides toString() to describe the
exception textually:
try { … }
catch (ArithmeticException e) {
[Link](“Exception: “ + e);
}
The following text will be displayed:
Exception: [Link]: / by zero
Multiple Catch Clauses
When more than one exception can be raised by a single piece of code, several catch clauses can be used with
one try block:
1) each catch catches a different kind of exception
2) when an exception is thrown, the first one whose type matches that of the exception is executed
3) after one catch executes, the other are bypassed and the execution continues after the try/catch block
Example: Multiple Catch 1
Two different exception types are possible in the following code: division by
zero and array index out of bound:
class MultiCatch {
public static void main(String args[]) {
try {
int a = [Link];
[Link]("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
Example: Multiple Catch 2
Both exceptions can be caught by the following catch clauses:
catch(ArithmeticException e) {
[Link]("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
[Link]("Array index oob: " + e);
}
[Link]("After try/catch blocks.");
}
}
Clauses
Order is important:
5|Page
Own Exception Handling

1) catch clauses are inspected top-down


2) a clause using a super-class will catch all sub-class exceptions
Therefore, specific exceptions should appear before more general ones. In particular, exception sub-classes
must appear before super-classes.
Example: Multiple Catch order 1
A try block with two catch clauses:
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
This exception is more general but occurs first:
} catch(Exception e) {
[Link]("Generic Exception catch.");
}
Example: Multiple Catch ORDER 2
This exception is more specific but occurs last:
catch(ArithmeticException e) {
[Link]("This is never reached.");
}
}
}
The second clause will never get executed. A compile-time error (unreachable code) will be raised.
Motivating finally
When an exception is thrown:
1) the execution of a method is changed
2) the method may even return prematurely.
This may be a problem is many situations. For instance, if a method opens a file on entry and closes on exit;
exception handling should not bypass the proper closure of the file. The finally block is used to address this
problem.
finally Clause
The try/catch statement requires at least one catch or finally clause, although both are optional:
try { … }
catch(Exception1 ex1) { … } …
finally { … }
Executed after try/catch whether of not the exception is thrown. Any time a method is to return to a caller from
inside the try/catch block via:
1) uncaught exception or
2) explicit return
the finally clause is executed just before the method returns.
Example: finally 1
Three methods to exit in various ways.
class FinallyDemo {
procA prematurely breaks out of the try by throwing an exception, the
finally clause is executed on the way out:
static void procA() {
try {
[Link]("inside procA");
throw new RuntimeException("demo");
} finally {
[Link]("procA's finally");
}
}
Example: finally 2
procB’s try statement is exited via a return statement, the finally clause is executed before procB returns:
6|Page
Own Exception Handling

static void procB() {


try {
[Link]("inside procB");
return;
} finally {
[Link]("procB's finally");
}
}
Example: finally 3
In procC, the try statement executes normally without error, however the finally clause is still executed:
static void procC() {
try {
[Link]("inside procC");
} finally {
[Link]("procC's finally");
}
}
Example: finally 4
Demonstration of the three methods:
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
[Link]("Exception caught");
}
procB();
procC();
}
}
Java Built-In Exceptions
The default [Link] package provides several exception classes, all sub-classing the RuntimeException class.
Two sets of build-in exception classes:
1) unchecked exceptions – the compiler does not check if a method handles or throws there exceptions
2) checked exceptions – must be included in the method’s throws clause if the method generates but does not
handle them

Unchecked Built -In Exceptions 1

7|Page
Own Exception Handling

Methods that generate but do not handle those exceptions need not declare them in the throws clause:

Checked Built-In Exceptions


Methods that generate but do not handle those exceptions must declare them in the throws clause:

ABSTARCTION
Abstract Method
Inheritance allows a sub-class to override the methods of its super-class.
In fact, a super-class may altogether leave the implementation details of amethod and declare such a method abstract:
abstract type name(parameter-list);
Two kinds of methods:
1) concrete
2) abstract
– may be overridden by sub-classes
– must be overridden by sub-classes
It is illegal to define abstract constructors or static methods.
Example: Abstract Method
The area method cannot compute the area of an arbitrary figure:
8|Page
Own Exception Handling

double area() {
[Link]("Area is undefined.");
return 0;
}
Instead, area should be defined abstract in Figure:
abstract double area() ;

Abstract Class
A class that contains an abstract method must be itself declared abstract:
abstract class abstractClassName {
abstract type methodName(parameter-list) {

}

}
An abstract class has no instances - it is illegal to use the new operator:
abstractClassName a = new abstractClassName();
It is legal to define variables of the abstract class type.
Abstract Sub-Class
A sub-class of an abstract class:
1) implements all abstract methods of its super-class, or
2) is also declared as an abstract class
abstract class A {
abstract void callMe();
}
abstract class B extends A {
int checkMe;
}
Abstract and Concrete Classes 1
Abstract super-class, concrete sub-class:
abstract class A {
abstract void callme();
void callmetoo() {
[Link]("This is a concrete method.");
}
}
class B extends A {
void callme() {
[Link]("B's implementation.");
}
}
Abstract and Concrete Classes 2
Calling concrete and overridden abstract methods:
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
[Link]();
[Link]();
}
}
Example: Abstract Class 1
Figure is an abstract class; it contains an abstract area method:
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a; dim2 = b;
}
abstract double area();
}
9|Page
Own Exception Handling

Example: Abstract Class 2


Rectangle is concrete – it provides a concrete implementation for area:
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
double area() {
[Link]("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
Example: Abstract Class 3
Triangle is concrete – it provides a concrete implementation for area:
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
double area() {
[Link]("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
Example: Abstract Class 4
Invoked through the Figure variable and overridden in their respective subclasses, the area() method returns the area of
the invoking object:
class AbstractAreas {
public static void main(String args[]) {
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
}
figref
figref
= r; [Link]([Link]());
= t; [Link]([Link]());
}
Abstract Class References
It is illegal to create objects of the abstract class:
Figure f = new Figure(10, 10);
It is legal to create a variable with the abstract class type:
Figure figref;
Later, figref may be used to assign references to any object of a concrete
sub-class of Figure (e.g. Rectangle) and to invoke methods of this class:
Rectangle r = new Rectangle(9, 5);
figref = r; [Link]([Link]());
Uses of final
The final keyword has three uses:
1) declare a variable which value cannot change after initialization
2) declare a method which cannot be overridden in sub-classes
3) declare a class which cannot have any sub-classes
(1) has been discussed before.
Now is time for (2) and (3).
Preventing Overriding with final
A method declared final cannot be overridden in any sub-class:
class A {
final void meth() {
[Link]("This is a final method.");
}
}
This class declaration is illegal:
10 | P a g e
Own Exception Handling

class B extends A {
void meth() {
[Link]("Illegal!");
}
}
final and Early Binding
Two types of method invocation:
1) early binding – method call is decided at compile-time
2) late binding – method call is decided at run-time
By default, method calls are resolved at run-time.
As a final method cannot be overridden, their invocations are resolved atcompile-time. This is one way to improve
performance of a method call.
Preventing Inheritance with final
A class declared final cannot be inherited – has no sub-classes.
final class A { … }
This class declaration is considered illegal:
class B extends A { … }
Declaring a class final implicitly declares all its methods final.
It is illegal to declare a class as both abstract and final.
Object Class
Object class is a super-class of all Java classes:
1) Object is the root of the Java inheritance hierarchy.
2) A variable of the Object type may refer to objects of any class.
3) As arrays are implemented as objects, it may also refer to any array.
Object Class Methods 1
Methods declared in the Object class:
1) Object clone() - creates an object which is an ideal copy of the invoking object.
2) boolean equals(Object object) - determines if the invoking object and the argument object are the same.
3) void finalize() – called before an unused object is recycled
4) Class getClass() – obtains the class description of an object at run-time
5) int hashCode() – returns the hash code for the invoking object
Object Class Methods 2
6) void notify() – resumes execution of a thread waiting on the invoking object
7) void notifyAll() – resumes execution of all threads waiting on the invoking object
8) String toString() – returns the string that describes the invoking object
9) three methods to wait on another thread of execution:
a) void wait()
b) void wait(long milliseconds)
c) void wait(long milliseconds, int nanoseconds)
Overriding Object Class Methods
All methods except getClass, notify, notifyAll and wait can beoverridden.
Two methods are frequently overridden:
1) equals()
2) toString()
This way, classes can tailor the equality and the textual description of objects to their own specific structure and needs.
Exercise: Polymorphism
Define a relationship among the following Building, HighBuildingand Skyscraper classes.
2) Define a class Visits that stores an array of 10 buildings (representing a street).
3) Define a method that enters all the buildings in the street using the method enter, one after another.
4) Fill the array with mixed objects from the classes Building, HighBuilding and Skyscraper.
Make sure, that the output of your program visualizes the fact that
different method implementations are used depending on the type of the
actual object.

Access

Name Space Management


11 | P a g e
Own Exception Handling

Classes written so far all belong to a single name space: a unique name has to be chosen for each class to avoid
name collision. Some way to manage the name space is needed to:
1) ensure that the names are unique
2) provide a continuous supply of convenient, descriptive names
3) ensure that the names chosen by one programmer will not collide
with those chosen by another programmers
Java provides a mechanism for partitioning the class name space into more manageable chunks. This
mechanism is a package

Package
A package is both a naming and a visibility control mechanism:
1) divides the name space into disjoint subsets It is possible to define classes within a package that are not
accessible by code outside the package.
2) controls the visibility of classes and their members It is possible to define class members that are only
exposed to other members of the same package.
Same-package classes may have an intimate knowledge of each other, but not expose that knowledge to other
packages.
Package Definition
A package statement inserted as the first line of the source file:
package myPackage;
class MyClass1 { … }
class MyClass2 { … }
means that all classes in this file belong to the myPackage package. The package statement creates a name
space where such classes are stored. When the package statement is omitted, class names are put into the
default package which has no name.
Multiple Source Files
Other files may include the same package instruction:
package myPackage;
class MyClass1 { … }
class MyClass2 { … }
package myPackage;
class MyClass3{ … }
A package may be distributed through several source files.
Packages and Directories
Java uses file system directories to store packages.
Consider the Java source file:
package myPackage;
class MyClass1 { … }
class MyClass2 { … }
The bytecode files [Link] and [Link] must be stored in a directory myPackage.
Case is significant! Directory names must match package names exactly.
Package Hierarchy
To create a package hierarchy, separate each package name with a dot:
package myPackage1.myPackage2.myPackage3;
A package hierarchy must be stored accordingly in the file system:
1) Unix
2) Windows
3) Macintosh
myPackage1/myPackage2/myPackage3
myPackage1\myPackage2\myPackage3
myPackage1:myPackage2:myPackage3
You cannot rename a package without renaming its directory!
Finding Packages
As packages are stored in directories, how does the Java run-time system
know where to look for packages?

12 | P a g e
Own Exception Handling

Two ways:
1) The current directory is the default start point - if packages are
stored in the current directory or sub-directories, they will be found.
2) Specify a directory path or paths by setting the CLASSPATH
environment variable.
CLASSPATH Variable
CLASSPATH - environment variable that points to the root directory of the system’s package hierarchy.
Several root directories may be specified in CLASSPATH, e.g. the current directory and the C:\myJava
directory:
.;C:\myJava
Java will search for the required packages by looking up subsequent directories described in the CLASSPATH
variable.
Finding Packages
Consider this package statement:
package myPackage;
In order for a program to find myPackage, one of the following must be true:
1) program is executed from the directory immediately above
myPackage (the parent of myPackage directory)
2) CLASSPATH must be set to include the path to myPackage
Example: Package 1
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n; bal = b;
}
void show() {
if (bal<0) [Link]("-->> ");
[Link](name + ": $" + bal);
}
}
Example: Package 2
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for (int i=0; i<3; i++) current[i].show();
}
}
Example: Package 3
Save, compile and execute:
1) call the file [Link]
2) save the file in the directory MyPack
3) compile; [Link] should be also in MyPack
4) set access to MyPack in CLASSPATH variable, or make the parent of MyPack your current directory
5) run:
java [Link]
Make sure to use the package-qualified class name.
Importing of Packages
Since classes within packages must be fully-qualified with their package names, it would be tedious to always
type long dot-separated names. The import statement allows to use classes or whole packages directly.
Importing of a concrete class:
13 | P a g e
Own Exception Handling

import [Link];
Importing of all classes within a package:
import myPackage1.myPackage2.*;
Access Control
Classes and packages are both means of encapsulating and containing the name space and scope of classes,
variables and methods:
1) packages act as a container for classes and other packages
2) classes act as a container for data and code
Access control is set separately for classes and class members.
Access Control: Classes
Two levels of access:
1) A class available in the whole program:
public class MyClass { … }
2) A class available within the same package only:
class MyClass { … }
Access Control: Members
Four levels of access:
1) a member is available in the whole program:
public int variable;
public int method(…) { … }
2) a member is only available within the same class:
private int variable;
private int method(…) { … }
Access Control: Members
3) a member is available within the same package (default access):
int variable;
int method(…) { … }
4) a member is available within the same package as the current class,
or within its sub-classes:
protected int variable;
protected int method(…) { … }
The sub-class may be located inside or outside the current package.
Access Control Summary
Complicated?
Any member declared public can be accessed from anywhere.
Any member declared private cannot be seen outside its class.
When a member does not have any access specification (default access), it
is visible to all classes within the same package.
To make a member visible outside the current package, but only to subclasses of the current class, declare this
member protected.

14 | P a g e
Own Exception Handling

Example: Access 1
Access example with two packages p1 and p2 and five classes.
A public Protection class is in the package p1.
It has four variables with four possible access rights:
package p1;
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
Example: Access 2
public Protection() {
[Link]("base constructor");
[Link]("n = " + n);
[Link]("n_pri = " + n_pri);
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
}
}
The rest of the example tests the access to those variables.
Example: Access 3
Derived class is in the same p1 package and is the sub-class of Protection.
It has access to all variables of Protection except the private n_pri:
package p1;
class Derived extends Protection {
Derived() {
[Link]("derived constructor");
[Link]("n = " + n);
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
}
}
Example: Access 4
SamePackage is in the p1 package but is not a sub-class of Protection.
It has access to all variables of Protection except the private n_pri:
package p1;
class SamePackage {
SamePackage() {
Protection p = new Protection();
[Link]("same package constructor");
}
[Link]("n = "
[Link]("n_pro
[Link]("n_pub
+
=
=
p.n);
" + p.n_pro);
" + p.n_pub);
}
Example: Access 5

Protection2 is a sub-class of [Link], but is located in a


15 | P a g e
Own Exception Handling

different package – package p2.


Protection2 has access to the public and protected variables of
Protection. It has no access to its private and default-access variables:
package p2;
class Protection2 extends [Link] {
Protection2() {
}
[Link]("derived
[Link]("n_pro =
[Link]("n_pub =
other package");
" + n_pro);
" + n_pub);
}
Example: Access 6

OtherPackage is in the p2 package and is not a sub-class of


[Link].
OtherPackage has access to the public variable of Protection only. It
has no access to its private, protected or default-access variables:
class OtherPackage {
OtherPackage() {
[Link] p = new [Link]();
[Link]("other package constructor");
[Link]("n_pub = " + p.n_pub);
}
}
Example: Access 7

A demonstration to use classes of the p1 package:


package p1;
public class Demo {
public static void main(String args[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}
Example: Access 8

A demonstration to use classes of the p2 package:


package p2;
public class Demo {
public static void main(String args[]) {
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
Import Statement
The import statement occurs immediately after the package statement and before the class statement:
package myPackage;
import otherPackage1;[Link];
class myClass { … }
The Java system accepts this import statement by default:
16 | P a g e
Own Exception Handling

import [Link].*;
This package includes the basic language functions. Without such functions,
Java is of no much use.
Name Conflict 1

Suppose a same-named class occurs in two different imported packages:


import otherPackage1.*;
import otherPackage2.*;
class myClass { … otherClass … }
package otherPackage1;
class otherClass { … }
package otherPackage2;
class otherClass { … }

Name Conflict 2

Compiler will remain silent, unless we try to use otherClass.


Then it will display an error message.
In this situation we should use the full name:
import otherPackage1.*;
import otherPackage2.*;
class myClass {

[Link]

[Link]

}
Short versus Full References

Short reference:
import [Link].*;
class MyClass extends Date { … }
Full reference:
class MyClass extends [Link] { … }
Only the public components in imported package are accessible for nonsub-classes in the importing code!
Example: Packages 1

A package MyPack with one public class Balance. The class has two same-package variables: public
constructor and a public show method.
package MyPack;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n; bal = b;
}
public void show() {
if (bal<0) [Link]("-->> ");
[Link](name + ": $" + bal);
}
}
Example: Packages 2

17 | P a g e
Own Exception Handling

The importing code has access to the public class Balance of the
MyPack package and its two public members:
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
Balance test = new Balance("J. J. Jaspers", 99.88);
[Link]();
}
}
Java Source File

Finally, a Java source file consists of:


1) a single package instruction (optional)
2) several import statements (optional)
3) a single public class declaration (required)
4) several classes private to the package (optional)
At the minimum, a file contains a single public class declaration.

Exercise: Access1
) Create a package emacao. Don't forget to insert your package into a directory of the same name. Insert a class
AccessTest into this packge. Define public, default and private data members and methods in your class AccessTest.
2) Define a second class Accessor1 in your package that accesses the different kinds of data members of methods
(private, public,default). See what compiler messages you get.
3) Define class Accessor2 outside the package. Again try to access all methods and data members of the class AccessTest.
See what compiler messages you get.
4) Where are the differences between Accessor1 and Accessor2

Interface

Using interface, we specify what a class must do, but not how it does this. An interface is syntactically similar to a class,
but it lacks instance variables and its methods are declared without any body. An interface is defined with an interface
keyword.

Interface Format

General format:
access interface name {
type method-name1(parameter-list);
type method-name2(parameter-list);

type var-name1 = value1;
type var-nameM = valueM;

}
Interface Comments

Two types of access:


1) public – interface may be used anywhere in a program
2) default – interface may be used in the current package only
Interface methods have no bodies – they end with the semicolon after the parameter list. They are essentially abstract
methods. An interface may include variables, but they must be final, static and initialized with a constant value. In a
public interface, all members are implicitly public.

Interface Implementation

A class implements an interface if it provides a complete set of methods defined by this interface.

18 | P a g e
Own Exception Handling

1) any number of classes may implement an interface


2) one class may implement any number of interfaces
Each class is free to determine the details of its implementation.
Implementation relation is written with the implements keyword.

Implementation Format
General format of a class that includes the implements clause:
access class name
extends super-class
implements interface1, interface2, …, interfaceN {

}
Access is public or default

Implementation Comments

If a class implements several interfaces, they are separated with a comma.


If a class implements two interfaces that declare the same method, the same method will be used by the clients of either
interface. The methods that implement an interface must be declared public. The type signature of the implementing
method must match exactly the type signature specified in the interface definition.
Example: Interface
Declaration of the Callback interface:
interface Callback {
void callback(int param);
}

Client class implements the Callback interface:

class Client implements Callback {


public void callback(int p) {
[Link]("callback called with " + p);
}
}

More Methods in Implementation


An implementing class may also declare its own methods:
class Client implements Callback {
public void callback(int p) {
[Link]("callback called with " + p);
}
void nonIfaceMeth() {
[Link]("Classes that implement “ +
“interfaces may also define ” +
“other members, too.");
}
}
Interface as a Type

Variable may be declared with interface as its type:


interface MyInterface { … }

MyInterface mi;
The variable of an interface type may reference an object of any class that
implements this interface.
class MyClass implements MyInterface { … }
MyInterface mi = new MyClass();
19 | P a g e
Own Exception Handling

Call Through Interface Variable

Using the interface type variable, we can call any method in the interface:
interface MyInterface {
void myMethod(…) ;

}
class MyClass implements MyInterface { … }

MyInterface mi = new MyClass();

[Link]();
The correct version of the method will be called based on the actual instance
of the interface being referred to.
Example: Call Through Interface 1

Declaration of the Callback interface:


interface Callback {
void callback(int param);
}
Client class implements the Callback interface:
class Client implements Callback {
public void callback(int p) {
[Link]("callback called with " + p);
}
}
Example: Call Through Interface 2

TestIface declares the Callback interface variable, initializes it with the


new Client object, and calls the callback method through this variable:
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
[Link](42);
}
}
Call Through Interface Variable 2

Call through an interface variable is one of the key features of interfaces:


1) the method to be executed is looked up dynamically at run-time
2) the calling code can dispatch through an interface without having to
know anything about the callee
Allows classes to be created later than the code that calls methods on them.
Example: Interface Call 1

Another implementation of the Callback interface:


class AnotherClient implements Callback {
public void callback(int p) {
[Link]("Another version of callback");
[Link]("p squared is " + (p*p));
}
}
Example: Interface Call 2

Callback variable c is assigned Client and later AnotherClient


objects and the corresponding callback is invoked depending on its value:
class TestIface2 {
public static void main(String args[]) {
20 | P a g e
Own Exception Handling

Callback c = new Client();


[Link](42);
AnotherClient ob = new AnotherClient();
c = ob;
[Link](42);
}
}
Compile-Time Method Binding
Normally, in order for a method to be called from one class to another, both classes must be present at compile time.
This implies:
1) a static, non-extensible classing environment
2) functionality gets pushed higher and higher in the class hierarchy to make them available to more sub-classes

Run-Time Method Binding

Interfaces support dynamic method binding.


Interface disconnects the method definition from the inheritance hierarchy:
1) interfaces are in a different hierarchy from classes
2) it is possible for classes that are unrelated in terms of the class hierarchy to implement the same interface

Interface and Abstract Class

A class that claims to implement an interface but does not implement all its methods must be declared abstract.
Incomplete class implements the Callback interface but not its callback method, so the class is declared abstract:
abstract class Incomplete implements Callback {
int a, b;
void show() {
[Link](a + " " + b); } }

Gui
Graphical User Interfaces in Java
• The fundamental elements that you need to
create a GUI reside in two packages, [Link]
and [Link].
• The [Link] package was the primary
repository to create GUI in Java1.1 (awt being
an abbreviation for Abstract Windowing Toolkit)
• but many of the classes this package defines
have been superseded in Java 2 by [Link]
Java Foundation Classes (JFC)
• JFC is a general set of GUI programming capabilities. It contains the following set of packages for creating GUI
– Swing component classes, such as those defining buttons and menus, but also
– Classes for 2D drawing from the [Link] package
– Classes that support drag-and-drop capability in the [Link] package.
– The JFC also includes an application program interface (API) defined in the [Link] package that allows
applications to be implemented that provide for users with disabilities.
Difference b/w AWT and Swing
• AWT is platform-dependent
• Swing is platform- Independent
• Swing is a more powerful package as compared to AWT and offers many enhanced elements as well

21 | P a g e
Own Exception Handling

Creating a Window

Window Example
import [Link];
public class TryWindow {
// The window object
static JFrame aWindow = new JFrame(“This is the Window
Title”);
public static void main(String[] args) {
int windowWidth = 400; // Window width in pixels
int windowHeight = 150; // Window height in pixels
[Link](50, 100, // Set position
windowWidth, windowHeight); // and size
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true); // Display the window
}
}

22 | P a g e
Own Exception Handling

Components and Containers

Basics of Components
• Component properties/attributes
•The position is stored as (x, y) coordinates. This fixes where the object is in relation to its container in the coordinate
system of the container object.

•The name of the component is stored as a String object.


•The size is recorded as values for the width and the height of the object.
•The foreground color and background color that apply to the object. These color values are used when the object is
displayed.
•The font used by the object when text is displayed.
•And many more……
Setting component color and font
Color myBlack = new Color(0,0,0); // Color black
Color myWhite = new Color(255,255,255); // Color white
Color myGreen = new Color(0,200,0); // A shade of green
[Link]().setBackground(myGreen)

23 | P a g e
ABSTARCTION

Swing Components
• Swing components all have the JComponent class as a base, which itself extends the Component class
• All the Swing component classes are defined in the [Link] package and have class names that begin with
J
• There are various useful classes in the swing package to deal with GUI
– Button
– Menus
– Text components…

24 | P a g e
Event handling

Buttons in Swing

Creating a Swing Button


Container content =
[Link]();
JButton myButton=new
JButton(“MyButton”);
[Link](myButton);

Setting Window Layout


FlowLayout flow = new
FlowLayout();
Container content =
[Link]();
[Link](flow);
Window Layouts

25 | P a g e
Event handling

Check Boxes and Radio Buttons


JRadioButton myRButton=new
RadioButton(“my radio button”);
[Link](myRButton);
JRadioButton myRButton=new
RadioButton(“my radio button”);
[Link](myRButton);
Adding Group of Radio Buttons
//Creating Radio Group
ButtonGroup radioGroup = new ButtonGroup();
//add a radio button
JRadioButton myRadioButton=new JRadioButton("Red");
[Link](myRadioButton);
[Link](myRadioButton);
//add another radio button
JRadioButton anotherRadioButton=new JRadioButton("Green");
[Link](anotherRadioButton);
[Link](anotherRadioButton);

26 | P a g e
Event handling

Adding Menu to a Window


// Create a menu Bar
JMenuBar menuBar = new JMenuBar();
//setting a menu bar of a window
[Link](menuBar);
//Creating a menu
JMenu fileMenu = new JMenu(“File”);
//adding menu to menu bar
[Link](fileMenu);
//Creating and adding menu items
JMenuItem openMenu = new JMenuItem(“Open”);
[Link](openMenu);
JCheckboxMenuItem circleItem = new JCheckboxMenuItem(“Circle”);
[Link](circleItm);
JRadioButtonMenuItem curveItem = new JRadioButtonMenuItem(“Curve”, true);
[Link](curveItem);
Swing Text Components

27 | P a g e
Event handling

Other important Swing components


• JPanel
– The JPanel class defines something like a physical panel that you can use as a container to group a set of components
• JTable
– JTable component implements a table of items from which you can select a row, a column, or a single element.
• JList
– A JList component implements a list of items with a line border around it.
Containers

Containers
• A container is any component of a type that has the Container class as a base; so all the Swing components are
containers
• The Container class is the direct base class for the Window class, and it provides the capability for a window to contain
other components
• Since the Container class is an abstract class, you cannot create instances of Container
Getting objects contained in a container

EVENT Handling

See SketchFrame Example


28 | P a g e
Event handling

• Method processWindowEvent() is defined in class Window


• Also see component class process….() methods
Listeners in java
• All event listeners in java inherit from [Link]
Event Listeners

29 | P a g e
Event handling

Components and Events they can generate

30 | P a g e
Event handling

Adapter Classes
• An adapter class is a term for a class that implements a listener interface with methods that have no content
• They do nothing
• This enable you to derive your own listener class from any of the adapter classes that are provided, and then
implement just the methods that you are interested in
• Its benefit is that
– You don’t need to implement all methods in a listener interface
Adapter classes for low level events

Handling Semantic Events


Class HandleButton implements ActionListener{
Public void action performed(ActionEvent e){
if ([Link]() ==button1)
{
left();
}
else if ([Link]() ==button2)
{
right();
}}}
Dealing with Text Fields
• Methods of JTextField class
• getText()
– Returns the string from the text field.
• setText(String text)
– Puts the given string in the text field.
• setEditable(boolean editable)
– Enables or disables the text field to be edited. By default, editableis true.
• setColumns(int)
31 | P a g e
Event handling

– Sets the number of columns in this text field.


– The length of the text field is changeable.
Dealing with Text Fields
• See TextFieldDemo example
Handling Menubar Events
• Use ActionListener interface
• Use method addActionListner() to bind the menu items with action listener.
• See MenuDemo example class for a complete example
Handling Events
• The signals that a program receives from the operating system as a result of your actions are called events.
• A window-based program is called an event-driven program
• because the sequence of events created as a result of your interaction with the GUI determines what happens

in the program.
Event-driven program
The Event-Handling Process
• An event always
has a source object
• Any event that is
passed to a Java
program will be
represented by a
particular event
object
• This object will
be passed as an
argument to the
method that is to
handle the event.
void

actionPerformed(ActionEvent e){

32 | P a g e
Event handling

// Handle the Event...


}
Event Classes
• Your program may need to respond to many different kinds of events
– from menus
– from buttons
– from the mouse, from the keyboard….
• At the topmost level, there are two broad categories of events in Java:
– Low Level events
– Semantic Events
Event types
• Low-Level Events—These are system-level events that arise from the keyboard or from the mouse, or
events associated with operations on a window, such as reducing it to an icon or closing it.
• Semantic Events—These are specific component related events such as pressing a button by clicking it to
cause some program action or adjusting a scrollbar.
Java Packages for events
• Most of the events relating to the GUI for a program are represented by classes that are defined in the
– [Link] package.
• The package
– [Link]
• defines classes for events that are specific to
Swing components.
• The AWTEvent class is itself a subclass of
– [Link].
Low-Level Event Classes

33 | P a g e
Event handling

Low-Level Event Classes

Constants defined in AWTEvent class

These constants represent each type of event in AWTEvent class


• You call the enableEvents() method for the component, and pass the constant for the events you want enabled
as an argument.
• See [Link] for an example
WindowEvent class event id’s

Event-Handling Methods

34 | P a g e
Event handling

Listener Objects
• A listener object is simply an object that listens for particular events.
• A listener is also called a target for an event.
• Each kind of listener interface defines particular methods for receiving the events that that listener has been designed to
deal with.
• Implement the listener interface to listen for events

35 | P a g e
Event handling

Associating Listener to souces


• Implementing the listener interface is not enough
• You need to associate sources (buttons, menu’s etc) with the listener
• For example
– To register a listener to listen for button-click events, you call the addActionListener() method for the JButton object
and pass the listener object as the argument to the method.
• All event listener interfaces extend the interface
[Link].
The WindowListener Interface

The MouseListener Interface

36 | P a g e
Event handling

Semantic Action Listeners

37 | P a g e

You might also like