• No results found

Unit3_Package_Interface.ppt

N/A
N/A
Protected

Academic year: 2020

Share "Unit3_Package_Interface.ppt"

Copied!
39
0
0

Loading.... (view fulltext now)

Full text

(1)

Packages :

Defining Package, CLASSPATH, Package naming, Accessibility of Packages ,

using Package Members.

Interfaces:

Implementing Interfaces, Interface and Abstract Classes, Extends and

(2)

Introduction

 The main feature of OOP is its ability to support

the reuse of code:

Extending the classes (via inheritance)Extending interfaces

 The features in basic form limited to reusing the

classes within a program.

 What if we need to use classes from other

programs without physically copying them into the program under development ?

 In Java, this is achieved by using what is known

(3)

Packages

Packages are Java’s way of grouping a number of

related classes and/or interfaces together into a single unit. That means, packages act as

“containers” for classes.

 The benefits of organising classes into packages

are:

The classes contained in the packages of other programs/applications can be reused.

In packages classes can be unique compared with classes in other packages. That two classes in two different

packages can have the same name. If there is a naming clash, then classes can be accessed with their fully

qualified name.

 Classes in packages can be hidden if we don’t want other packages to access them.

Packages also provide a way for separating “design” from coding.

(4)

Java Foundation Packages

Java provides a large number of classes groped into

(5)

Using System Packages

 The packages are organised in a hierarchical

structure. For example, a package named “java” contains the package “awt”, which in turn contains various classes required for

implementing GUI (graphical user interface).

Graphics Font java

Image awt

lang “java” Package containing

“lang”, “awt”,.. packages; Can also contain classes.

awt Package containing classes

Classes containing methods

(6)

Creating and Naming

Packages

Java supports a keyword called “package” for creating

user-defined packages. The package statement must be the first statement in a Java source file (except

comments and white spaces) followed by one or more classes.

 Package name is “myPackage” and classes are

package myPackage;

public class ClassA { // class body }

class ClassB { // class body }

(7)

Creating Sub Packages

 Classes in one ore more source files can be

part of the same packages.

As packages in Java are organised

hierarchically, sub-packages can be

created as follows:

package myPackage.Math

package myPackage.secondPakage.thirdPackage

 Store “thirdPackage” in a subdirectory named

“myPackage\secondPackage”. Store

“secondPackage” and “Math” class in a subdirectory “myPackage”.

(8)

Accessing a Package

As indicated earlier, classes in packages

can be accessed using a fully qualified

name or using a short-cut as long as we

import a corresponding package.

The general form of importing package

is:

 import package1[.package2][…].classname  Example:

 import myPackage.ClassA;

import myPackage.secondPackage

 All classes/packages from higher-level

(9)

Using a Package

 Let us store the code listing below in a file

named “ClassA.java” within subdirectory named “myPackage” within the current directory (say “abc”).

package myPackage;

public class ClassA { // class body

public void display() {

System.out.println("Hello, I am ClassA"); }

}

class ClassB { // class body

(10)

Using a Package

Within the current directory (“abc”) store

the following code in a file named

“ClassX.java”

import myPackage.ClassA;

public class ClassX {

public static void main(String args[]) {

ClassA objA = new ClassA(); objA.display();

(11)

Compiling and Running

When ClassX.java is compiled, the

compiler compiles it and places .class

file in current directly. If .class of ClassA

in subdirectory “myPackage” is not

found, it comples ClassA also.

Note: It does not include code of ClassA

into ClassX

When the program ClassX is run, java

loader looks for ClassA.class file in a

package called “myPackage” and loads

it.

(12)

Classpath

Compiled classes can be stored in different

locations in the file systems.

How to locating these files – Setting a

classpath which is a list of directories where

class files should be searched

e.g. If Java system is to find classes from the machines.vehicles.cars package , its

classpath must point to C:\A\B\classes, the root of the package directory hierarchy.

(13)

Setup Classpath

 In command line

c:\> java –classpath C:\A\B\classes machines.vehicles.cars.Car

 To avoid specify the classpath in every command,

set classpath as a command shell environment variable:

Windows:

>set CLASSPATH = C:\A\B\classes >set CLASSPATH = .; %CLASSPATH% >echo %CLASSPATH%

.; C:\A\B\classes  Unix:

$CLASSPATH = $HOME/A/B/classes $CLASSPATH = .: $CLASSPATH

(14)

Classpath for .zip and .jar File

JDK can open .zip and .jar archives and

search for class files inside.

The archives must store class files within

the appropriate directory structure.

Set up classpath for archives:

(15)

Accessibility of Packages:

Protection and Packages

All classes (or interfaces) accessible to all

others in the same package.

Class declared public in one package is

accessible within another. Non-public class is

not

Members of a class are accessible from a

difference class, as long as they are not

private

protected

members of a class in a package

are accessible to subclasses in a different

class

(16)

Visibility - Revisited

Public

keyword applied to a class, makes it

available/visible everywhere. Applied to a

method or variable, completely visible.

Private

fields or methods for a class only

visible within that class. Private members

are

not

visible within subclasses, and are

not

inherited.

Protected

members of a class are visible

within the class, subclasses and

also

within

all classes that are in the same package as

(17)

Visibility Modifiers

Accessible to: public protected Package (default)

private

Same Class Yes Yes Yes Yes

Class in package Yes Yes Yes No

Subclass in

different package

Yes Yes No No

Non-subclass different package

(18)

Adding a Class to a Package

Consider an existing package that

contains a class called “Teacher”:

This class is stored in “Teacher.java” file

within a directory called “pack1”.

How do we a new public class called

“Student” to this package.

package pack1;

public class Teacher {

// class body }

(19)

Adding a Class to a

Package

 Define the public class “Student” and place the

package statement before the class definition as follows:

 Store this in “Student.java” file under the directory

“pack1”.

 When the “Student.java” file is compiled, the class

file will be created and stored in the directory “pack1”. Now, the package “pack1” will contain both the classes “Teacher” and “Student”.

package pack1;

public class Student {

// class body }

class Teacher package pack1;

(20)

Packages and Name Clashing

 When packages are developed by different

organizations, it is possible that multiple

packages will have classes with the same name, leading to name classing.

We can import and use these packages like:

import pack1.*;

class Teacher package pack1;

class Student

class Student package pack2;

(21)

Handling Name Clashing

In Java, name classing is resolved by

accessing classes with the same name

in multiple packages by their fully

qualified name.

Example:

import pack1.*; import pack2.*;

pack1.Student student1; pack2.Student student2;

Teacher teacher1; Courses course1;

(22)

Extending a Class from

Package

A new class called “Professor” can be

created by extending the “Teacher” class

defined the package “pack1” as follows:

import pack1.Teacher;

public class Professor extends Teacher {

// body of Professor class

// It is able to inherit public and protected members, // but not private or default members of Teacher class. }

(23)

using Package Members :

Accessing Classes from

Packages

There are two ways of accessing the classes stored in

packages:

Using fully qualified class name

java.lang.Math.sqrt(x);

Import package and use class name directly.

import java.lang.MathMath.sqrt(x);

Selected or all classes in packages can be imported:

 Implicit in all programs: import java.lang.*;  package statement(s) must appear first

import package.class; import package.*;

(24)

Using a Package

 Let us store the code listing below in a file

named “ClassA.java” within subdirectory named “secondPackage” within the current directory (say “abc”).

package secondPackage;

public class ClassC { // class body

public void display() {

System.out.println("Hello, I am ClassC"); }

(25)

Using a Package

Within the current directory (“abc”) store

the following code in a file named

“ClassX.java”

import myPackage.ClassA; import secondPackage.ClassC;

public class ClassY {

public static void main(String args[]) {

ClassA objA = new ClassA(); ClassC objC = new ClassC(); objA.display();

objC.display(); }

(26)

Interfaces

A public interface is a contract between client code and

the class that implements that interface.

A Java interface is a formal declaration of such a contract

in which all methods contain no implementation.

Many unrelated classes can implement the same

interface.

 A class can implement many unrelated interfaces.  Syntax of a Java class is as follows:

<modifier> class <name> [extends <superclass>][implements <interface> [,<interface>]* ]

{

<member_declaration>*}

(27)

Uses of Interfaces

Interface uses include the following:

 Declaring methods that one or more classes

are expected to implement

 Capturing similarities between unrelated

classes without forcing a class relationship

 Simulating multiple inheritance by declaring

(28)

Interface

Unlike with the singly inherited class

hierarchy, you can include as many

interfaces as you need in your own class,

and your class will implement the

combined behavior of all the included

interfaces

(29)

Interface

What happens if 2 different interfaces

both define the same method?

 If the method in each of the interfaces have

identical signatures, you can implement one method in your class and that definition

satisfies both interfaces.

 If the methods have different parameters list

than it’s a simple case of method overloading.

(30)

Interface

Interface can declare constants.

The constants are implicitly public, static,

final – these key words are not required in

the interface declaration.

All methods in interface are implicitly

(31)

Interface

Recall that when a class implements an

interface, the class makes a contract with a

complier stating either that the class will

implements each of the methods in the

interface or that the class must be declared

as abstract.

(32)

Interface vs. Abstract Class

An interface is simply a list of

unimplemented, and therefore abstract,

methods.

An interface cannot implement any

methods, whereas an abstract class can.

A class can implement many interfaces

but can have only one superclass.

An interface is not part of the class

(33)

Defining an Interface

Defining an interface is similar to creating a

new class.

An interface definition has two components:

the interface declaration and the interface body.

interfaceDeclaration

{

interfaceBody

}

 The interfaceDeclaration declares various

attributes about the interface such as its name and whether it extends another interface.

(34)

public interface StockWatcher {

final String sunTicker = "SUNW"; final String oracleTicker = "ORCL"; final String ciscoTicker = "CSCO"; void valueChanged

(String tickerSymbol, double newValue); }

If you do not specify that your interface is public, your interface will be accessible only to classes

(35)

Implementing an Interface

 Include an implements clause in the class

declaration.

 A class can implement more than one

interface (the Java platform supports multiple inheritance for interfaces), so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

 When implement an interface, either the class

must implement all the methods declared in the interface and its superinterfaces, or the class must be declared abstract

(36)

class C {

public static final int A = 1; }

interface I {

public int A = 2; }

class X implements I {

public static void main (String[] args) {

int I = C.A, j = A; …

(37)

public class StockMonitor

implements StockWatcher

{ ...

public void valueChanged

(String tickerSymbol, double newValue) {

if (tickerSymbol.equals(sunTicker)) { ... }

else if

(tickerSymbol.equals(oracleTicker)) { ... }

else if (tickerSymbol.equals(ciscoTicker)) { ... }

(38)

Properties of Interface

A new interface is a new reference data

type.

Interfaces are not instantiated with

new,

but they have certain properties similar to

ordinary classes

You can declare that an object variable will

be of that interface type

e.g.

Comparable x = new Tile(…); Tile y = new Tile(…);

(39)

Extends and implements

A class can extends properties of one class and

implements features of Interface.

 You can provide more information about the class, such

as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class

declaration.

For example,

class MyClass extends MySuperClass implements YourInterface

{

// field, constructor, and // method declarations }

means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.

References

Related documents

Series may contain: Correspondence between the office and insurance companies, agents, policyholder; copies of insurance policies; copies of Agreed Orders Retain in Agency one (1)

• No Visible effect for launch of Migraine Drug • Learning will be useful for future products • Cost

Findings of the study are clear indicators that public libraries can provide services that can help boost the employability of job seekers These services show that Nigerian

To respond to this event, this JFrame class must implement the ActionListener interface and define an actionPerformed() method, as shown here:.. public class MyGUIController

The increase in the rate of return from the “safe” crop investment reduces the actuarially fair crop insurance effect on “risky” crop investment if the farmers have CARA preference

Due to the exceptional situation caused by the health crisis of the COVID-19 and taking into account the security measures related to the development of the

Can she declare a reference variable of excel array literal whose component type species an unbounded wildcard parameterized type.. Note the use of

Our model gives two important characterisations of bubbles in economics: firstly, a rapid super-exponential growth; secondly, an illusion of certainty as described by a