Packages and Class Visibility The objectives of this chapter are: To understand logical class groupings using packages To explain the environment variable.

Slides:



Advertisements
Similar presentations
Packages Sudhir Talasila Preeti Navale. Introduction Packages are nothing more than the way we organize files into different directories according to.
Advertisements

UML Package Diagrams. package_name presentation view controller model.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 Chapter 12 More OOP, Interfaces, and Inner Classes.
Road Map Introduction to object oriented programming. Classes
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
EEC-681/781 Distributed Computing Systems Java Tutorial Wenbing Zhao Cleveland State University
Java Programming Chapter 3 More about classes. Why?  To make classes easier to find and to use  to avoid naming conflicts  to control access  programmers.
1 Lecture 2 Java Packages  What are Java packages?  Why do wee need packages?  How to create a Java package?  Some examples.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
Chapter 10 Classes Continued
Unit 051 Packages What is a Package? Why use Packages? Creating a Package Naming a Package Using Package Members Managing Source and Class Files Visibility.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
Lecture 9 Polymorphism Richard Gesick.
1 Lecture 2: Object Oriented Programming in Java.
Dale Roberts Object Oriented Programming using Java - Packages Dale Roberts, Lecturer Computer Science, IUPUI Department.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Chapter 8: Inner Classes. You're an OO programmer, so you know that for reuse and flexibility/extensibility you need to keep your classes specialized.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Introduction to programming in the Java programming language.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
EE2E1. JAVA Programming Lecture 3 Java Programs and Packages.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
By Waqas The topmost class in the java class hierarchy is called “Object”. If you declare a class which does not sub class of any super class.
(C) 2010 Pearson Education, Inc. All rights reserved. abstract class Employee represents the general concept of an employee. Subclasses: SalariedEmployee,
22-July-2002cse142-13B-Development © 2002 University of Washington1 Development Tools CSE 142, Summer 2002 Computer Programming 1
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Packages. Creating and Using Packages To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
Package A package is a logical container that contains classes,interfaces sub packages. Package provide a unique name space to its members and provide.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Packages. Access Specifications Public Available anywhere (public keyword) Only one public class per file allowed Protected Available in subclasses, and.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
CS 884 (Prasad)Java Names1 Names Scope and Visibility Access Control Packages.
CS116 COMPILER ERRORS George Koutsogiannakis 1. How to work with compiler Errors The Compiler provide error messages to help you debug your code. The.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Methods. Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Java Package Advantage of Java Package
UNIT-3 Interfaces & Packages. What is an Interface? An interface is similar to an abstract class with the following exceptions: All methods defined in.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
 2005 Pearson Education, Inc. All rights reserved. 1 Classes and Objects: A Deeper Look.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
Java Packages - allow you to group classes as a collection Standard Java library has packages: java.lang and java.util … Also hierarchical: java and javax.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Packages When we name a program , we name it by class name…
Java Basics Packages.
Nested class.
Lecture 23 Polymorphism Richard Gesick.
Separate Compilation and Namespaces
Java Programming Language
Inheritance Dr. Bhargavi Goswami Department of Computer Science
Packages and Interfaces
Introduction to Classes and Objects
Applying OO Concepts Using Java
Abstract Classes and Interfaces
SPL – PS1 Introduction to C++.
Presentation transcript:

Packages and Class Visibility The objectives of this chapter are: To understand logical class groupings using packages To explain the environment variable CLASSPATH To describe inner and anonymous classes and their uses

Abstraction and Class Namespaces Because classes are an abstraction of real world objects, choosing the correct name for classes can lead to ambiguities This is confounded when classes are taken "out of context" One of the main purposes of packages is to provide a contextual namespace within which a class resides A class called "Stock" may have several meanings A class called "Stock" in the inventory package is much less ambiguous Java provides a syntax for package names Package names are separated by periods Packages can contain classes or packages The fully qualified name of a class includes its package name: inventory.Stock indicates a class called "Stock" within the "inventory" package.

Java and A Global Namespace The designers of Java have proposed an Internet-wide unique package naming scheme It includes the Internet domain name of the organization within which the package was developed. The domain is reversed and the subdomains become packages afox.org becomes org.afox The domain portion is prepended to any packages developed within afox.org financial.inventory.Stock becomes org.afox.financial.inventory.Stock This standard guarantees that no other organization will create a class whose name conflicts with classes developed with afox.org.

Putting classes in packages To put a class into a package, one uses the "package" statement The package statement MUST be the first line of code within the file. It can be proceeded by comments. If no package statement is supplied, the class is placed in the "default" package The default package is a package with no name package org.afox.financial.inventory; public class Stock { [...] in file Stock.java:

Making it all work with Import Unfortunately, the proposed naming scheme creates very long names for classes A class which was originally named "Stock" is now named "org.afox.financial.inventory.Stock". This makes coding difficult. It dramatically reduces code readability. To avoid having to use the fully qualified class name for all classes, the programmer can "import" some or all of the classes from a given package Once a class has been imported, it need only be referenced by its name. ie "Stock" instead of "org.afox.financial.inventory.Stock" // Import a single class import org.afox.financial.inventory.Stock; // Import all classes from the specified packages import org.afox.financial.inventory.*; import java.io.*; import java.net.*;

Notes on the import statement Import ONLY imports public classes from the specified package Classes which are not public cannot be referenced from outside their package. There is no way to "import all classes except one" import either imports a single class or all classes within the package Note: importing has no runtime or performance implications. It is only importing a namespace so that the compiler can resolve class names. Import statements must appear at the top of the file after the package statement and before any class or interface definitions.

Compiling classes with packages Packages provide a logical namespace for classes When compiled, the package structure is physically represented using a directory structure The.class file for the class "org.afox.financial.inventory.Stock" will reside a the following path: org/afox/financial/inventory/Stock.class Package names map directly to subdirectories The programmer can specify the root of the package directory structure using the -d option with the javac compiler. javac -d /home/schock/classes Stock.java Will cause the compiler to place the.class file at: /home/schock/classes/org/afox/financial/inventory/Stock.class

Resolving Packages at Runtime The Java compiler compiles.java files to.class files Each compiled class resides within its own.class file Classes are loaded into the virtual machine by the ClassLoader Because of packages,.class files can now exist within a large number of directories For performance reasons, the ClassLoader must have a quick way of resolving a fully qualified class reference to.class file. Resolving packages to directories is simple. However, the virtual machine must know where to find the directory structure The ClassLoader uses an environment variable called CLASSPATH to find the directory which contains the package directories.

CLASSPATH Setting the CLASSPATH has been the bane of many programmers You never really learn how to swear until you try to set the CLASSPATH The CLASSPATH is a variable that contains a list of directories which are separated by colons (:) Note: Under the Windows OS, they are separated by semicolons (;) The the ClassLoader attempts to load a class, it searches for the.class file using the CLASSPATH, Package name and class name: If CLASSPATH="/home/schock/classes:/usr/development/classes" the class loader will search for the Stock class in the following locations: /home/schock/classes/org/afox/financial/inventory/Stock.class /usr/development/classes/org/afox/financial/inventory/Stock.class

More on CLASSPATH The ClassLoader searches the directories in the CLASSPATH in the order in which they are defined When the ClassLoader finds a class, it loads it and stops searching Place higher priority directories earlier in the CLASSPATH If no class is found, the ClassLoader throws a NoClassDefFoundError NOTE:.class files can be archived within.zip files or.jar files. When archived, the directory structure is preserved. CLASSPATH can ALSO contain.jar or.zip files. When the ClassLoader encounters a.jar or.zip file within the CLASSPATH, it searches through the.jar or.zip file the same way it would search in a directory. Java applications are distributed in.jar file form.

.jar files.jar files are created using the jar command The jar command is included with the Java SDK distribution Note: The.jar file format is the SAME as the.zip file format See the Java SDK Documentation for the jar program. Jar files can be defined with a main class. If a.jar file has a main class defined, it can be executed using the following command: java -jar filename.jar

Is CLASSPATH important at compile time? The previous slides have shown how the ClassLoader uses CLASSPATH to find.class files at runtime. CLASSPATH is also used by the compiler to resolve association issues If an object sends a message to another object, the compiler must ensure that the receiving object responds to the message. The receiving object's class must be loaded by the compiler and checked. If the receiving objects class has already been compiled, the above process works. However, what if the class has not yet been compiled and no.class file exists? The compiler attempts to locate the receiving object's.java file (using CLASSPATH) in an attempt to compile it. This means your source file structure MUST ALSO match the package directory structure. The root of your source tree MUST ALSO be within your CLASSPATH

Non-public classes As noted earlier, the import statement imports public classes only Non-public classes can be defined in different ways nested classes(Defined within a class) inner classes member classes(similar to nested classes) local classes(defined within a method) anonymous classes(classes with no name!) These forms of defining classes have been provided as an implementational convenience. Unfortunately, the use of these types of classes can rapidly decrease code readability. Use with care. Nested and inner classes have a special relationship to the outer class which defines them: Access to private variables and methods.

Nested Classes Nested classes are defined WITHIN another class They are defined using the static keyword The nested class is defined as part of the outer class. It can only be referenced through the outer class. public class LinkedList { private static class LinkedListNode { [...] } public static class LinkedListStats { [...] } // Create an instance of the nested class LinkedListStats LinkedList.LinkedListStats x = new LinkedList.LinkedListStats(); // Illegal access to private nested class -- compiler error LinkedList.LinkedListNode y = new LinkedList.LinkedListNode();

Member Classes Member classes are similar to nested classes, except they are not static. They are used in the same manner as instance variables. public class LinkedList { public class LinkedListStats { [...] } LinkedList aList = new LinkedList(); LinkedList.LinkedListStats aStat = new aList.LinkedListStats();

Local Classes Local classes are defined within a method The scope is limited to the method Used for small helper classes whose applicability is within the method only public class LinkedList { public void traverse() { class MyIterator extends Iterator { public void doTraversal() { [...] } MyIterator anIterator = new MyIterator(); [...] }

Anonymous inner Classes Anonymous classes have no name They are declared and instantiated in one step. Used to create a quick subclass of an existing class where one or more method is overridden. public class LinkedList { private ListChangeDelegate aDelegate; public LinkedList() { aDelegate = new ListChangeDelegate(){ [ override methods here ] }

Inner classes --.class file names All Java classes are compiled to their own.class file The compiler gives special names to inner class.class files For nested, member and local classes Outer$Inner.class For anonymous classes Outer$1.class Outer$2.class All inner class.class files contain the $ character. To avoid confusion, it is recommended that one avoids naming classes using the $ character.

Non-public classes Non-public classes do not need to be defined within another class. They can be defined externally to a class, but within the same.java file. public class LinkedList { [... Linked List class definition and Methods...] } class LinkedListNode { [... helper class definition... ] } class LinkedListStats { [... another helper class definition... ] } in file LinkedList.java: