Extending The Classes (Via Inheritance) Extending Interfaces

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

PACKAGES

 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 as “packages”, a concept similar to “class libraries” in other
languages.

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.

Java Foundation Packages

 Java provides a large number of classes groped into different packages based on their functionality.

The six foundation Java packages are:


java.lang:Contains classes for primitive types, strings, math functions, threads, and exception
java.util :Contains classes such as vectors, hash tables, date etc.
java.io :Stream classes for I/O
java.awt: Classes for implementing GUI – windows, buttons, menus etc.
java.net:Classes for networking
java.applet: Classes for creating and implementing applets
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).

Creating Packages / Importing Packages

1. Define a public class. If the class is not public, it can be used only by otherclasses in the same package.

2. Choose a package name, and add a package statement to the source code file forthe reusable class
definition. [Note: There can be only one package statement ina Java source code file.]

3. Compile the class so it is placed in the appropriate package directory structure.

4. Import the reusable class into a program, and use the class.
 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 “csePackage” and classes are considred as part of this package; The code is saved in a file
called “Arithmetic.java” and located in a directory called “csePackage”.

csePackage

Arithrmetic.java
protected int x;
protected inty;
public int add();
public int subtraction();
public int multiplication;
public float division()

Package csePackage;

Public class Arithmetic {

Public int x, y;

public Arithmetic() {
x = 0;
y = 0;
}

Public int addition() {


int z = x + y;
return z;
}

Public int subtraction() {


int z = x - y;
return z;
}

Public int multiplication() {


int z = x * y;
return z;
}

Public float division() {


float z = x / y;
return z;
}
}
Import csePackage.*;

Public classArithmeticTest {
Public static void main( String args[])
{
Arithmetic arth = newArithmetic();

arth.x = 7;
arth.y = 5;

int sum = arth.addition();


System.out.println("Sum = " + sum );

int diff = arth.subtraction();


System.out.println("Difference = " + diff );

int product = arth.multiplication();


System.out.println("Multiplication = " + product );

float quotient = arth.division();


System.out.println("DivisionResult = " + quotient );
}
}

OUTPUT
Sum = 12
Difference = 2
Multiplication = 35
DivisionResult = 1.0

Access Protection
Java addresses four categories of visibility for class members:
■ Subclasses in the same package
■ Non-subclasses in the same package
■ Subclasses in different packages
■ Classes that are neither in the same package nor subclasses

 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

Visibility – in Packages
 Publickeyword applied to a class, makes it available/visible everywhere. Applied to a
method or variable, completely visible.

 Privatefields or methods for a class only visible within that class. Private members are not
visible within subclasses, and are not inherited.

 Protectedmembers of a class are visible within the class, subclasses and also within all
classes that are in the same package as that class.

 Default: members of a class are visible within the class and subclasses of the same package
only
Class Member Access
Private NoModifier Protected Public

Same class yes yes yes yes

Same package No yes yes yes


subclass

Same package No yes yes yes


non-subclass

Different package No no yes Yes


subclass

Different package No No No yes


non-subclass

P1

Protection
SamePackage
int n = 1;
private intn_pri = 2;
protected intn_pro = 3;
public intn_pub = 4;

Derived

P2

Protection2
OtherPackage
//Protection.java
package p1;
public class Protection {

int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;

public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

//Derived.java
package p1;

class Derived extends Protection {

Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

//SamePackage.java
package p1;

class SamePackage {

SamePackage()
{
Protection p = newProtection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
P1Test.java
package p1;

publicclass P1Test {

public static void main(String args[]) {


Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}

OUTPUT

base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
derived constructor
n=1
n_pro = 3
n_pub = 4
base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
same package constructor
n=1
n_pro = 3
n_pub = 4

//Protection2.java
package p2;

class Protection2 extends p1.Protection {

Protection2() {
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
package p2;

classOtherPackage {

OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}

//P2Test.java
package p2;

public class P2Test {

public static void main(String args[]) {

Protection2 ob1 = new Protection2();


OtherPackage ob2 = new OtherPackage();
}
}

OUTPUT
base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
derived other package constructor
n_pro = 3
n_pub = 4
base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
other package constructor
n_pub = 4

import
The import directive tells the compiler where to look for the class definitions when it comes upon a class
that it cannot find in the default java.lang package. So, for example, in the class definition below for
TestABC, the import statements
importmypack.*;
import csePackage.*;
importjava.applet.*;

indicate that classes can be found in the mypack and csePackage , packages and also that the Applet
class can be found in the java.applet package

The package directory names become part of the class name after the class is compiled.

The fully qualified name of the class name is actually casePackage.Arithmetic after the class is compiled and
placed in a package

We can either use the fully qualified name(csePackage.Arithmeticarth = new


caePackageArithmetic() ) of the class or

we can import the package and use its short name *i.e Arithmetic arth = new Arithmetic()

eg…
Using fully qualified name
public class ArithmeticTest{
public Static void main(String args[] )
{
csePackage.Arithmeticarth = new caePackageArithmetic();
}
}

Using the short name of the class

importcsePackage.*;
public class ArithmeticTest{
public static void main(String args[] )
{
Arithmetic arth = new Arithmetic();
}
}

import java.io.*;
.* will import all the .class files present in the io package

importjava.io.BufferedReader;
will import Buffered Reader .class file only

Namespace

In addition to organizing classes in a clearly defined manner, packages also prevent name collisions.
That is, if you use classes from other sources, it is inevitable that eventually duplicate class names
will occur. If they are in different packages, however, this is not a problems since their full package
names would differ.
vrkWomens shadan

CseStudent CseStudent

String roll#; String roll#;


String Year; String Year;

public labPercent(); public labPercent();


public theoryPercent(); public theoryPercent();

When packages are developed by different organizations, it is possible that multiple packages will
have classes with the same name, leading to name clashing.

 We can import and use these packages like:

 importvrkWomens.*;

 importshadan.*;

 cseStudent student1; // Generates compilation error when the student object is created

 In Java, name classing is resolved by accessing classes with the same name in multiple packages by
their fully qualified name.

Example:

importvrkWomens.*;
importshadan.*;

public class VrkShadanTest{


public static void main(String args[] )
{
//using fully qualified name of class to resolve the naming conflict.
vrkWomens.cseStudentstudent1 = new vrkWomens.cseStudent(“II Year”, “06H81A05551”);;
shadan.cseStudentstudent2 = new shadan.cseStudent(“II Year”, “07458255625”);
……….

}
CLASSPATH
The class path can be set using either the -classpath option when calling an SDK tool (the preferred method) or by setting
the CLASSPATH environment variable. The -classpath option is preferred because you can set it individually for each
application without affecting other applications and without other applications modifying its value.

C:>sdkTool-classpathclasspath1;classpath2...

-or-

C:>set CLASSPATH=classpath1;classpath2...

where:

sdkTool
A command-line tool, such as java, javac, or javadoc..

Setting CLASSPATH

The CLASSPATH environment variable is modified with the set command. The format is:

set CLASSPATH=path1;path2 ...


Understanding the class path and package names

Understanding the class path and package names


Java classes are organized into packages which are mapped to directories in the file system. But, unlike the file system,
whenever you specify a package name, you specify the whole package name -- never part of it. For example, the package
name for java.awt.Button is always specified as java.awt.

For example, suppose you want the Java runtime to find a class named Cool.class in the package utility.myapp. If the
path to that directory isC:\java\MyClasses\utility\myapp, you would set the class path so that it contains
C:\java\MyClasses.

To run that app, you could use the following JVM command:

C:>java -classpath C:\java\MyClasses utility.myapp.Cool

When the app runs, the JVM uses the class path settings to find any other classes defined in the utility.myapp package
that are used by the Cool class.

Note that the entire package name is specified in the command. It is not possible, for example, to set the class path so it
contains C:\java\MyClasses\utility and use the command java myapp.Cool. The class would not be found.

(You may be wondering what defines the package name for a class. The answer is that the package name is part of the
class and cannot be modified, except by recompiling the class.)

Note: An interesting consequence of the package specification mechanism is that files which are part of the same
package may actually exist in different directories. The package name will be the same for each class, but the path to
each file may start from a different directory in the class path.

Multiple specifications

To find class files in the directory C:\java\MyClasses as well as classes in C:\java\OtherClasses, you would set the class
path to:

C:>java -classpath C:\java\MyClasses;C:\java\OtherClasses ...


Adding a Class to a Package
 Consider an existing package named “Engg” that contains a class called “Engg2To4.java”:
 This class is stored in “Engg2To4.java” file within a directory called “Engg”.
Engg

Engg2To4

int s1, s2, s3, s4, s5, s6;


int l1, l2;

public float theoryPercent();


public float labPercent();

 How do we a new public class called “Engg4_2.java” to this package.


Engg4_2

protected int seminar;


protected int project;

public float projectPercent();

Adding a Class to a Package


 Define the public class “Engg2_4.java” and place the package statement before the class
definition as follows:
packageEngg;
public class Engg4_2
{……
……..
}

 Store this in “Engg2_4.java” file under the directory “Engg”.

Engg

Engg4_2.java Engg2_4.java

 When the “Engg2_4.java” file is compiled, the class file will be created and stored in the directory
“Engg”. Now, the package “Engg” will contain both the classes “Engg2To4.java” and
“Engg2_4.java”.
Engg

Engg2To4

int s1, s2, s3, s4, s5, s6;


int l1, l2;

public float theoryPercent();


public float labPercent();

Engg4_1

protected int seminar;


protected int project;

public float projectPercent();

Engg

Engg4_2

int s1, s2, s3;


int l1, l2;

public float theoryPercent();

package Engg2_4;

public class Engg2To4 {

int s1, s2, s3, s4, s5, s6;


int l1, l2;

public floatlabsPercentage()
{
float labpercent = (l1 + l2) / 150 * 100;
return labpercent;
}
public float theoryPercentage() {
float theorypercent = (l1 + l2) / 150 * 100;
return theorypercent;
}
}
package Engg2_4;

public class Engg4_1


{
protected int seminar;
protected int project;

public float projectpercentage()


{
float pp = (seminar + project) / 200 * 100;
return pp;
}
}
Package Engg2_4;

Public class Engg4_2 extends Engg2_4.Engg4_1{

Private int s1, s2, s3;

Public float theoryPercentage()


{
Float theoryPercentage = ( s1 + s2 + s3 );
Return theoryPercentage;

Public float projectPercentage()


{
Float pp = ( seminar + project )/ 300 * 100;
}

You might also like