ee2e1. java programming lecture 3 java programs and packages

29
EE2E1. JAVA Programming Lecture 3 Lecture 3 Java Programs and Java Programs and Packages Packages

Upload: samson-thompson

Post on 04-Jan-2016

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

EE2E1. JAVA Programming

Lecture 3Lecture 3

Java Programs and PackagesJava Programs and Packages

Page 2: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

Contents

Java source files and class filesJava source files and class files Packages Packages public/package/private scopepublic/package/private scope The The CLASSPATHCLASSPATH environment variable environment variable

Page 3: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

Java source files and class files

Java progams execute on the Java Virtual Java progams execute on the Java Virtual Machine (JVM) which is usually Machine (JVM) which is usually implemented as an interpreter and executed implemented as an interpreter and executed with the with the javajava command command

Java source code is compiled to Java source code is compiled to bytecodebytecode by by the compiler executed with the the compiler executed with the javacjavac commandcommand

Page 4: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

public class Test{

public static void main(String[] args)

{ System.out.println(“Hi!”);}

}

Java source file Test.java

Java compiler

Java bytecodeJava class file Test.class

Java interpreter (JVM)

Hi!

Page 5: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

The name of the source file (The name of the source file (Test.javaTest.java)) matches the name of the public classmatches the name of the public class ((TestTest) ) and produces a bytecode file and produces a bytecode file Test.classTest.class

Only one public class per file is allowed Only one public class per file is allowed (see later - public/package/private scope)(see later - public/package/private scope)

A source file can contain any number of A source file can contain any number of classes and compilation produces a classes and compilation produces a .class.class file for each class in the source filefile for each class in the source file

Page 6: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

Packages Java groups classes into Java groups classes into packagespackages

The standard Java library is distributed over a number of The standard Java library is distributed over a number of packages including packages including java.langjava.lang, , java.utiljava.util indicating sub- indicating sub-packagespackages

java.lang java.lang automatically imported into your programsautomatically imported into your programs

Contains a lot of the basic classes we use (Contains a lot of the basic classes we use (String,System String,System etc)etc)

We can create our own packages using the We can create our own packages using the packagepackage keyword keyword

In the following example, classes A and B are in the package In the following example, classes A and B are in the package my_packagemy_package

Page 7: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

package my_package;package my_package;

class Aclass A{{

// A’s public & private members// A’s public & private members}}

class Bclass B{{

// B’s public & private members// B’s public & private members}}

Page 8: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

The default package

If a source file If a source file does notdoes not begin with the begin with the packagepackage statement, the classes contained in statement, the classes contained in the source file reside in the the source file reside in the default packagedefault package

The java compiler automatically looks in The java compiler automatically looks in the default package to find classes (see the default package to find classes (see later)later)

It then searches all imported packages to It then searches all imported packages to find the remaining classes (see later)find the remaining classes (see later)

Page 9: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

Importing packages

The The importimport statement imports packages by statement imports packages by directing the compiler where to lookdirecting the compiler where to look

The The importimport statement in a Java program statement in a Java program must occur before any class definitionmust occur before any class definition

Either the whole package or a sub-package Either the whole package or a sub-package can be importedcan be imported

Either all of the classes in a package can be Either all of the classes in a package can be imported or just a particular class from the imported or just a particular class from the packagepackage

Page 10: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

import my_package.*;import my_package.*; // Imports all of the classes// Imports all of the classes

class Cclass C{{

// Can refer directly to classes A & B// Can refer directly to classes A & B

private A a;private A a;private B b;private B b;

}}

import my_package.A;import my_package.A; // Imports class A only// Imports class A only

class Cclass C{{

// Can refer directly to class A only// Can refer directly to class A only

private A a;private A a;private my_package.B b;private my_package.B b;

}}

Page 11: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

public/package/private scope Scope Scope is concerned with the visibility of program is concerned with the visibility of program

elements such as classes and memberselements such as classes and members

Both classes and class members (methods or instance Both classes and class members (methods or instance fields) can be defined with public, package or private fields) can be defined with public, package or private scope scope

A class with A class with public scopepublic scope means it is visible outside its means it is visible outside its containing packagecontaining package

Allows Java to find a class (maybe with the help of Allows Java to find a class (maybe with the help of CLASSPATH (see later)) as it must be in a file with CLASSPATH (see later)) as it must be in a file with the same name as the public classthe same name as the public class

Page 12: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

A class member with A class member with publicpublic scope scope means it is means it is visible anywhere its class is visiblevisible anywhere its class is visible

A class member with A class member with privateprivate scope scope means it is means it is visible only within its encapsulating classvisible only within its encapsulating class

A class/class member with A class/class member with package scopepackage scope means means it is visible only inside its containing packageit is visible only inside its containing package

Page 13: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

Example 1

package my_package;package my_package;

class Aclass A // package scope// package scope{{

// A’s public & private members// A’s public & private members}}

public class Bpublic class B // public scope// public scope{{

// B’s public and private members// B’s public and private members}}

Page 14: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

class A has no private/public label and thus class A has no private/public label and thus has, by default, package scopehas, by default, package scope

class B has public scopeclass B has public scope

class A is visible only within the package class A is visible only within the package but class B is visible outside the package but class B is visible outside the package alsoalso

Page 15: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

package another_package;package another_package;import my_package.*;import my_package.*;

class Cclass C{{

// C’s public & private members// C’s public & private members

// class C ‘knows’ about class B // class C ‘knows’ about class B

private B b;private B b; // OK – class B has public scope// OK – class B has public scope

}}

Page 16: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

package my_package;package my_package;

class Dclass D{{

// D’s public & private members// D’s public & private members

// Class D ‘knows’ about classes A and B // Class D ‘knows’ about classes A and B

private B b;private B b; // OK – class B has public scope// OK – class B has public scopeprivate A a;private A a; // OK – class A has package scope// OK – class A has package scope

}}

Page 17: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

Example 2package my_package;package my_package;class Aclass A{{

int get() { return data; }int get() { return data; } // package scope// package scopepublic A(int d) { data=d;}public A(int d) { data=d;} // public scope// public scopeprivate int data;private int data; // private scope// private scope

}}

class Bclass B{{

void f()void f(){{

A a=new A(d);A a=new A(d); // OK A has package scope// OK A has package scope int d=a.get();int d=a.get(); // OK – get() has package scope// OK – get() has package scope int d1=a.data;int d1=a.data; // Error! – data is private// Error! – data is private

}}}}

Page 18: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

Even though member function Even though member function A() A() has public has public scope, because class A only has package scope, scope, because class A only has package scope, the class and hence all of its member functions are the class and hence all of its member functions are only visible inside the packageonly visible inside the package

If member functions are to be publicly visible, If member functions are to be publicly visible, the class itself has to have public scopethe class itself has to have public scope

In general, classes and their members should be In general, classes and their members should be given the given the narrowestnarrowest possible scope appropriate possible scope appropriate to their functionalityto their functionality

Page 19: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

The CLASSPATH environment variable

The compiler and runtime interpreter know how to The compiler and runtime interpreter know how to find standard packages such as find standard packages such as java.langjava.lang and and java.utiljava.util

The CLASSPATH environment variable is used to The CLASSPATH environment variable is used to direct the compiler and interpreter to where direct the compiler and interpreter to where programmer defined imported packages can be foundprogrammer defined imported packages can be found

This then allows the This then allows the publicpublic class in the file to be class in the file to be foundfound

The CLASSPATH environment variable is an ordered The CLASSPATH environment variable is an ordered list of directories and fileslist of directories and files

Page 20: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

Example CLASSPATH’sExample CLASSPATH’s

WindowsWindows

UNIXUNIX

A A jarjar file is a file is a JJava ava ararchive file and is a collection chive file and is a collection of java class files (with the .class extension)of java class files (with the .class extension)

‘‘.’ means the current directory. In some Java .’ means the current directory. In some Java implementations, this is part of the CLASSPATH implementations, this is part of the CLASSPATH by default but normally has to be addedby default but normally has to be added

.;C:\java;C:\java\my_jar_file.jar.;C:\java;C:\java\my_jar_file.jar

.; /home/java; /home/java/my_jar_file.jar.; /home/java; /home/java/my_jar_file.jar

Page 21: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

The above directories and jar files are searched in the order The above directories and jar files are searched in the order they appear in the CLASSPATH list for imported they appear in the CLASSPATH list for imported packagespackages

The CLASSPATH list can be overridden with the –The CLASSPATH list can be overridden with the –classpath option to the compiler :classpath option to the compiler :

(javac –classpath …) (javac –classpath …)

and the interpreter and the interpreter

(java –classpath …)(java –classpath …) All files in a package must be in a sub-directory that All files in a package must be in a sub-directory that

matches the full package name matches the full package name Eg. all files in package Eg. all files in package my_package.sub-packagemy_package.sub-package are in are in

a sub-directory a sub-directory my_package/sub-package my_package/sub-package (Unix) which (Unix) which branches off one of the directories in the CLASSPATHbranches off one of the directories in the CLASSPATH

Page 22: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

// source file “my_package/A.java”// source file “my_package/A.java”

package my_package;package my_package;public class Apublic class A{{

int get() { return data; }int get() { return data; }public A(int d) { data=d;}public A(int d) { data=d;}private int data;private int data;

}}

// source file “TestA.java”// source file “TestA.java”

import my_package.A;import my_package.A;public class TestApublic class TestA{{

public static void main(String[] args){public static void main(String[] args){A a=new A(100); }A a=new A(100); }

}}

Page 23: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

class class TestATestA is in the default package is in the default package

Package/sub-package directory matches the Package/sub-package directory matches the directory/sub-directory structuredirectory/sub-directory structure

Default package

Package my_package

. (current directory)

Package

Sub-package

./my_package

Directory

Sub-directory

Page 24: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

Example We can create a We can create a PolygonPolygon class which represents a class which represents a

polygon as an array of points (vertices)polygon as an array of points (vertices)

The The PointPoint class is imported as part of a class is imported as part of a (programmer defined) geometrical package (programmer defined) geometrical package geomgeom

A method A method perimeter()perimeter() computes the polygon’s computes the polygon’s perimiterperimiter

class class PolygonTestPolygonTest contains a contains a mainmain method to test method to test the the PolygonPolygon class class

Page 25: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

package geom;package geom;

public class Pointpublic class Point{{

public Point(int x, int y)public Point(int x, int y){ xpos=x; ypos=y;}{ xpos=x; ypos=y;}

public int getX()public int getX(){{ return xpos;}return xpos;}

public int getY()public int getY(){ return ypos; }{ return ypos; }

private int xpos, ypos;private int xpos, ypos;}}

Page 26: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

import geom.Point;import geom.Point;public class Polygonpublic class Polygon{{

public Polygon(int n, Point[] v) public Polygon(int n, Point[] v) { {

numVertices=n; vertices=new Point[n];numVertices=n; vertices=new Point[n]; System.arraycopy(v,0,vertices,0,n);System.arraycopy(v,0,vertices,0,n);

}}

public double perimeter()public double perimeter(){{

double pm=0; int nn;double pm=0; int nn; for (int n=1; n<numVertices; n++)for (int n=1; n<numVertices; n++) {{ int xv1= vertices[n-1].getX(); int yv1=vertices[n-1].getY();int xv1= vertices[n-1].getX(); int yv1=vertices[n-1].getY(); nn=n%numVertices;nn=n%numVertices; int xv=vertices[nn].getX(); int yv=vertices[nn].getY();int xv=vertices[nn].getX(); int yv=vertices[nn].getY(); pm+=(Math.sqrt((xv1-xv)*(xv1-xxv)+(yv1-yv)*(yv1-yv)));pm+=(Math.sqrt((xv1-xv)*(xv1-xxv)+(yv1-yv)*(yv1-yv))); }} return pm;return pm;

}}private Point[] vertices;private Point[] vertices;private int numVertices;private int numVertices;

}}

Page 27: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

import geom.Point;import geom.Point;public class PolygonTestpublic class PolygonTest{{

public static void main(String[] args)public static void main(String[] args){{

Point[] pointArray={new Point(0,0), new Point(0,1), Point[] pointArray={new Point(0,0), new Point(0,1), new Point(1,1), new Point(1,0)};new Point(1,1), new Point(1,0)};

Polygon square=new Polygon(4,pointArray);Polygon square=new Polygon(4,pointArray);

double perim=square.perimeter();double perim=square.perimeter(); System.out.println(“The perimeter is ” + perim);System.out.println(“The perimeter is ” + perim);

}}}}

Page 28: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

class Point is in the class Point is in the geomgeom package whereas classes package whereas classes Polygon Polygon and and PolygonTestPolygonTest are in the default package are in the default package

File File Point.javaPoint.java will reside in a sub-directory will reside in a sub-directory geomgeom of the of the current directorycurrent directory

class class PointPoint is made public so it is visible outside of its is made public so it is visible outside of its packagepackage

The The geomgeom package could be expanded to include other basic package could be expanded to include other basic geometrical entities (line, curve etc)geometrical entities (line, curve etc)

Default package

Polygon.java

PolygonTest.java

Sub-package geom

Point.java

Directory ‘.’

Sub-directory geom

Page 29: EE2E1. JAVA Programming Lecture 3 Java Programs and Packages

And finally…. When writing seriously large Java applications, When writing seriously large Java applications,

you will create many classes and several packagesyou will create many classes and several packages Related classes will be grouped into packagesRelated classes will be grouped into packages

When you use a Java API, you normally have to When you use a Java API, you normally have to set up the CLASSPATH environment variable so set up the CLASSPATH environment variable so that its classes can be importedthat its classes can be imported Its important to understand the use of Its important to understand the use of

CLASSPATHCLASSPATH However, for your lab exercises, keeping all of However, for your lab exercises, keeping all of

your public classes in files with the same name as your public classes in files with the same name as the class in the current directory (default package) the class in the current directory (default package) will ensure all public classes are visiblewill ensure all public classes are visible