Vous êtes sur la page 1sur 26

Java classes and packages Java classes and packages

Lecture 6
Packages Packages
To make types easier to find and use, to avoid naming conflicts, and to
control access, programmers bundle groups of related types into
k packages.
Java classes always exist in a class package
Including those we define in our programs Including those we define in our programs
There is a default package which doesnt have a name
Java core API is made up of several packages
Class names in a package are qualified by the package name
e.g Math class has the fully qualified name as java.lang.Math
Introduction to Java 2
Uses of packages Uses of packages
The names of your classes and interfaces won't conflict with the
names in other packages because the package creates a new
namespace.
To create different class name spaces To create different class name spaces
Names used for classes in one package will not interfere with the
names of classes in another package
Copackage classes enjoy special access to each other members
Y d t h t i t th l You dont have to import those classes
Introduction to Java 3
Creating packages
Add a package statement as the first statement in your source file
containing the class definition
O l t d bl k li ll d t d th k Only comments and blank lines are allowed to precede the package
statement
A package statement consist of the keyword package followed by
h k i d b i l the package name terminated by a semicolon.
You can specify a package name as a sequence of names separated
by periods. y p
If you do not use a package statement, your type ends up in an
unnamed package
Use an unnamed package only for small or temporary applications p g y p y pp
Packages are intimately related to the directory structure in which
they are stored
Introduction to Java 4
Class files must be in a directory named by the package
Placing a class in a Package Placing a class in a Package
To place a class in a package, we write the following To place a class in a package, we write the following
as the first line of the code (except comments)
package <packageName>; p g p g ;
package myownpackage;
Example of a Package Example of a Package
package SchoolClasses; p g ;
public class StudentRecord {
private String name;
private String address;
private int age;
.
}
Using classes in a Package Using classes in a Package
To use a public package member (classes and
interfaces) from outside its package, you must
do one of the following
Import the package member using import
statement
Import the member's entire package using import
statement
Refer to the member by its fully qualified name
(without using import statement)
Importing Packages Importing Packages
To be able to use classes outside of the package
you are currently working in you need to import you are currently working in, you need to import
the package of those classes.
// Importing a class
import java.util.Date;
// Importing all classes in the java.util package
import java.util.*;
//Using fully qualified names
java.util.Date x = new java.util.Date();
Package & Directory Structure Package & Directory Structure
Packages can also be nested. In this case, the Java Packages can also be nested. In this case, the Java
interpreter expects the directory structure containing
the executable classes to match the package hierarchy.
There should be same directory structure, y
./myowndir/myownsubdir/myownpackage directory for
the following package statement
Package myowndir.myownsubdir.myownpackage;
Example Example
// in the Rectangle java file // in the Rectangle.java file
package graphics;
public class Rectangle() { public class Rectangle() {
}
Place the source file in a directory whose Place the source file in a directory whose
name reflects the name of the package to
which the class belongs which the class belongs
.....\graphics\Rectangle.java
Directory Structure of Java Source
l Files
Like the java source files the compiled class Like the .java source files, the compiled .class
files should be in a series of directories that
reflect the package name reflect the package name
Example
class name: graphics Rectangle class name: graphics.Rectangle
pathname to source file: graphics/Rectangle.java
pathname to the class file: graphics/Rectangle class pathname to the class file: graphics/Rectangle.class
Directory Structure of Java Source
l Files
However, the path to the .class files does not have to
be the same as the path to the .java source files. You
can arrange your source and class directories
separately, as: p y
<path_one>\sources\com\example\graphics\Rectangle.java
<path_two>\classes\com\example\graphics\Rectangle.class
By doing this, you can give the classes directory to y g , y g y
other programmers without revealing your sources
You also need to manage source and class files in this
manner so that the compiler and the Java Virtual manner so that the compiler and the Java Virtual
Machine (JVM) can find all the types your program
uses
Setting classpath Setting classpath
suppose we place the package schoolClasses under the C:\ pp p p g \
directory.
We need to set the classpath to point to that directory so that
h t t it th JVM ill b bl t h when we try to run it, the JVM will be able to see where our
classes are stored.
we type this at the command prompt, yp p p ,
C:\schoolClasses> set classpath=C:\
After setting the classpath we can now run our program After setting the classpath, we can now run our program
anywhere by typing,
C:\schoolClasses> java schoolClasses.StudentRecord
Setting classpath Setting classpath
Take note that you can set the classpath Take note that you can set the classpath
anywhere. You can also set more than one
classpath we just have to separate themby classpath, we just have to separate them by
;(for windows)
set classpath=C:\myClasses;D:\;E:\MyPrograms\Java set classpath C:\myClasses;D:\;E:\MyPrograms\Java
Inheritance Inheritance
Inheritance Inheritance
Defining a new class based on an existing class is called
derivation derivation
The derived class is also called the direct subclass of the
base or super class p
You can also derive classes from the derived class and so
on
Class A
Class B Class B
Class C
Inheritance Inheritance
class B extends A{
//definition of class B //definition of class B
}
The keyword extends identifies that class B is a direct The keyword extends identifies that class B is a direct
subclass of class A
The class B can have additional members in addition to the
inherited members of class A
Inheritance Inheritance
An inherited member of a base class is one that is
accessible within the derived class
Base class members that are not inherited still form part of
a derived class object
An inherited member of a derived class is a full member of
that class and is freely accessible to any method in the
class class
Which members of the base class are inherited?
Inheriting Data Members Inheriting Data Members
The inheritance rules apply to class variables as well as
instance variables
SubClass
SubClass
bli B Cl
SubClass
public BaseClass
int a
public int b; public int b;
protected int c;
private int d;
Inheritance Inheritance
You can define a data member in a derived class with the same name
d t b i th b l as data member in the base class.
The data member of the base class is still inherited but is hidden by
the derived class member with the same name
The hiding will occur irrespective if the type or access modifiers are
the same or not.
A f h d i d b ill l f h b Any use of the derived member name will always refer to the member
defined in derived class
To refer to the inherited base class member, you must qualify it with
the keyword super
Note that you cannot use super.super.something
Inheriting Methods Inheriting Methods
Methods in a base class excluding constructors are inherited in a g
derived class in the same way as the data members of the base class
Methods declared as private in a base class are not inherited
Note Constructors in the base class are never inherited regardless of Note: Constructors in the base class are never inherited regardless of
their attributes
Though the base class constructors are not inherited in your derived
class you can still call themor if you dont call a base class constructor class, you can still call them or if you dont call a base class constructor
from your derived class constructor, the compiler will try to do it for
you
The super class constructor is called in a subclass using super ( ); The super class constructor is called in a subclass using super ( );
Constructors Constructors
If the first statement in a derived class constructor is not a call to a
b l h il ill i ll h d f l base class constructor, the compiler will insert a call to the default
class constructor i.e super ( ), for you
Default call for base class constructor is with no arguments. This
sometimes result in a compiler error. Why?
When you define your own constructor in a class, no
default constructor is created by the compiler. Thus you
have to define the no argument constructor for the class have to define the no argument constructor for the class
yourself so that in a derived class you dont get the
compile error due to call to default constructor of base
class
Example p
public class Person {
protected String name;
protected String address;
/* Default constructor */
public Person() {
System.out.println(Inside Person:Constructor)
name "" address "" name = ""; address = "";
}. . . .
}
public class Student extends Person {
public Student()
{ System.out.println(Inside Student:Constructor);
}}. . . .
}
public static void main( String[] args ){
Student ann = newStudent(); Student ann new Student();
}
The super keyword The super keyword
A subclass can also explicitly call a constructor of its
immediate super class immediate super class.
This is done by using the super constructor call.
A super constructor call in the constructor of a subclass will p
result in the execution of relevant constructor from the super
class, based on the arguments passed.
F hi b h i h Few things to remember when using the super constructor
call:
The super() call must occur as the first statement in a constructor The super() call must occur as the first statement in a constructor
The super() call can only be used in a constructor (not in ordinary
methods)
Super Keyword Example Super Keyword Example
public Student(){
super( "SomeName" "SomeAddress" ) super( "SomeName", "SomeAddress" );
System.out.println("Inside Student:Constructor");
}
Another use of super is to refer to members of the super class
(just like the this reference ) (just like the this reference ).
public Student() {
super.name = somename;
super.address = some address;
}
Object Class Object Class
Object class is mother of all classes
In Java language, all classes are subclassed (extended)
from the Object super class
Object class is the only class that does not have a parent Object class is the only class that does not have a parent
class
Defines and implements behavior common to all Defines and implements behavior common to all
classes including the ones that you write
getClass()
equals()
toString()

Vous aimerez peut-être aussi