Module4oop Part2

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

OBJECT ORIENTED

PROGRAMMING WITH
JAVA
Department of Computer Science & Engineering

www.cambridge.edu.in
Packages
• A java package is a container for grouping similar types of classes, interfaces and sub-packages, providing
access protection and namespace management.
(i.e) Each package in java has its unique name and organizes its classes and interfaces into a separate
namespace, or name group.
• Think of it as a folder in a directory structure –Packages helps organize classes into a folder structure.
• Package is an encapsulation mechanism to group related classes and interfaces into a single unit.
• For example – A package allows us to create a class named List, which we can store in our own package without
concern that it will collide with some other class named List stored elsewhere.
• Although interfaces and classes with the same name cannot appear in the same package, they can appear in
different packages.
• Suppose we want to perform database operation – required classes are grouped into a single unit
(i.e) java.sql package.
• Ex : Existing packages in Java : java.lang -- consists of fundamental classes, java.io -- consists of I/O classes.
Packages
• Packages are divided into two categories:
• Built-in Packages (packages from the Java API) - java, lang, awt, javax,
swing, net, io, util, sql etc.
• User-defined Packages (We can create our own packages)
• Packages are stored in a hierarchical manner.
Advantages of Java Package
1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained and reused.
public class Test obj=new
2) Java package removes naming collision. (Without package statement we Test Test()

can’t have two different classes with same name. However, We can have mypack2
mypack1
two different classes with same name in two different packages)
3) Java package provides access protection. Package is both naming and a class Test
Test obj=new Test()
visibility control mechanism. we can define classes inside a package that are
not accessible by code outside that package.
mypack1
mypack2
Packages - Defining a Package
• To create a package is quite easy: simply include a package command as the first statement in a Java source
file.
• Any classes declared within that file will belong to the specified package.
• The package statement defines a name space in which classes are stored. If we omit the package
statement, the class names are put into the default package, which has no name.
• While the default package is fine for short, sample programs, it is inadequate for real applications.
• This is the general form of the package statement: package pkg;
• Here, pkg is the name of the package. For example, the following statement creates a package called
mypackage. package mypackage;
• The package name may be written in lower case to avoid conflict with class names.
Packages - Defining a Package
• More than one file can include the same package statement. The package statement simply specifies to which package the
classes defined in a file belong.

• It does not exclude other classes in other files from being part of that same package. Most real-world packages are spread across
many files.
• We can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period.
Multilevel package statement General Form is:
package pkg1[.pkg2[.pkg3]];
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
Packages - Finding Packages and CLASSPATH
How does the Java run-time system know where to look for packages that we create?
• First, by default, the Java run-time system uses the current working directory as its starting
point. Thus, if the package is in a subdirectory of the current directory, it will be found.
• Next, we can use the -classpath option with java to specify the path to the classes.
How to compile java file that contains package
• If we are not using any IDE, we need to follow the syntax given below:
• javac -d directory filename.java
• For example javac -d . Simple.java
• The -d switch specifies the destination where to put the generated class file.
• We can use any directory name like, d:\abc .
• If we want to keep the package within the same directory, we can use . (dot).
Packages - Finding Packages and CLASSPATH
How to run java package program
• We need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


Output
To Run: java mypack.Simple Welcome to package

• The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
• The . represents the current folder.
• How to send the class file to another directory or drive? To Compile:
javac -d d:\abc Simple.java
To Run:
java -classpath d:\abc mypack.Simple

Output
Welcome to package
Packages - Finding Packages and CLASSPATH
• The standard of defining package is domain.company.package e.g. com.sun.java
• Example of Subpackage
package com.neha.pack1;
public class Demo
{
public static void main(String args[])
{
System.out.println("Welcome to subpackage");
}
}

To Compile: javac -d . Demo.java

To Run: java com.neha.p1.Demo

Output
Welcome to subpackage
Packages – Importing Packages
• There is no core Java classes in the unnamed default package; all of the standard classes are stored in some named
package.
• How to access package from another package?
• There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name (it is tedious to type in the long dot-separated package path name for every class we want to
use)
• Since classes within packages must be fully qualified with their package name or names, it could become tedious to
type in the long dot-separated package path name for every class we want to use.
• For this reason, Java includes the import statement to bring certain classes, or entire packages, into visibility.
• Once imported, a class can be referred to directly, using only its name.
• The import statement is a convenience to the programmer and is not technically needed to write a complete Java
program.
• If we are going to refer to a few dozen classes in our application, however, the import statement will save a lot of
typing.
• In a Java source file, import statements occur immediately following the package statement (if it exists) and before
any class definitions.
Packages – Importing Packages
• This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
• Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the
outer package separated by a dot (.).
• Finally, we specify either an explicit classname or a star (*)
import java.util.Date;
import java.io.*;
• The star form may increase compilation time—especially if we import several large packages.
• For this reason it is a good idea to explicitly name the classes that we want to use rather than importing whole
packages.
• However, the star form has absolutely no effect on the run-time performance or size of our classes.
Packages – Importing Packages
• All of the standard Java classes included with Java are stored in a package called java.
• The basic language functions are stored in a package inside of the java package called
java.lang.
• Normally, we have to import every package or class that we want to use, but since Java is
useless without much of the functionality in java.lang, it is implicitly imported by the
compiler for all programs.
• This is equivalent to the following line being at the top of all of our programs: import
java.lang.*;
• If a class with the same name exists in two different packages that we import using the star
form, the compiler will remain silent, unless we try to use one of the classes.
Packages – Importing Packages
• In that case, we will get a compile-time error and have to explicitly name the class specifying its package.
• Example – java.util package has a class named, Date. Similarly, java.sql package has a class named, Date.
import java.sql.*;
import java.util.*;
class MyDate extends Date {
}
Compile-time error occurs.
• So, we will use fully qualified name as below
import java.sql.*;
import java.util.*;
class MyDate extends java.util.Date {
}
• In this version, Date is fully-qualified.
• when a package is imported, only those items within the package declared as public will be available to non-subclasses in the
importing code.
Packages – Importing Packages
//save by A.java
package pack1;
public class A
1) Using packagename.* {
If we use package.* then all the public void msg()
classes and interfaces of this {
package will be accessible but not System.out.println("Hello");
sub packages. }
} Output
The import keyword is used to //save by B.java Hello
make the classes and interface of package pack2;
another package accessible to the import pack1.*;
current package. public class B
Example of package that import {
the packagename.* public static void main(String[] args)
{
A obj=new A();
obj.msg();
}
}
Packages – Importing Packages
//save by A.java
package pack1;
public class A
2) Using packagename.classname {
public void msg()
If we import package.classname {
then only declared class of this System.out.println("Hello");
package will be accessible. }
Example of package using : }
//save by B.java
import package.classname; package pack2;
import pack1.A;
public class B
{
public static void main(String[] args)
{ Output
A obj=new A(); Hello
obj.msg();
}
}
Packages – Importing Packages
//save by A.java
package pack1;
public class A
3) Using fully qualified name
{
• If we use fully qualified name then public void msg()
only declared class of this package {
will be accessible. Now there is no System.out.println("Hello");
need to import. But we need to use }
fully qualified name every time when } Output
we are accessing the class. //save by B.java Hello
• It is generally used when two package pack2;
packages have same class name e.g. public class B
java.util and java.sql packages {
contain Date class. public static void main(String[] args)
{
• Example of package using : pack1.A obj=new pack1.A();
import fully qualified name obj.msg();
}
}
Packages – Importing Packages
Note: If we import a package, sub packages will not be
imported.
• If we import a package, all the classes and interface of that
package will be imported excluding the classes and interfaces
of the subpackages. Hence,we need to import the
subpackage as well.
• Note: Sequence of the program must be package then import
then class.
• package statement – only one package statement in a source
file.
• import statement – any number of import statements.
• classes – any number of classes.
Packages - Access Protection
• Packages act as containers for classes and other subordinate packages. Classes act as containers for data and
code. The class is Java’s smallest unit of abstraction.
• Because of the interplay between classes and packages, 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
• The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
• When a class is public, it must be the only public class declared in the file, and the file must have the same
name as the class.
There are four types of Java access modifiers: (private, default, protected and public)
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
Packages - Access Protection
2. Default (does not have an explicit access specification ): The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If we do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the package through child
class. If we do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the
class, within the package and outside the package.
Packages – Access Protection
package pack1;
class A
• Private - The private access {
modifier is accessible only within private int data=100;
the class. private void msg()
{
• In this example, we have created System.out.println("hello");
two classes A and Simple. A class }
}
contains private data member and public class Simple
private method. {
• We are accessing these private public static void main(String[] args) {
A ob=new A();
members from outside the class, so ob.msg(); //comile time error
there is a compile-time error. System.out.println(ob.data); //comile time error
}
}
Packages – Role of Private Constructor
If we make any class constructor private, we cannot create the
Access instance of that class from outside the class.
class A
Protection {
private A()
{

}
public void msg()
{
System.out.println("hello");
}
}
public class Simple
{
public static void main(String[] args) {
A ob=new A(); //compile time error
}
}
Packages – Access Protection
//save by A.java
package pack1;
public class A
Default
{
• If we don't use any modifier, it is treated void msg()
as default by default. {
• The default modifier is accessible only within System.out.println("hello");
package. }
• It cannot be accessed from outside the package. }
//save by B.java
• It provides more accessibility than private. But, it package pack2;
is more restrictive than protected, and public. import pack1.A;
Example of default access modifier public class B {
• In this example, we have created two packages public static void main(String[] args) {
pack1 and pack2. A ob=new A();
ob.msg(); //compile time error
• We are accessing the A class from outside its }
package, since A class is public, so it can be
accessed from outside the package. However, its }
method msg() has default access and cannot be In the above example, the scope of method msg() is default so it
accessed outside the package. cannot be accessed from outside the package.
Packages – Access Protection
//save by A.java
package pack1;
public class A
Protected {
• The protected access modifier is accessible protected void msg()
within package and outside the package but {
through inheritance only. System.out.println(“Hello");
• The protected access modifier can be applied on }
the data member, method and constructor. }
//save by B.java
• It can't be applied on the class.
package pack2;
• It provides more accessibility than the default import pack1.A;
modifer. public class B extends A {
Example of protected access modifier public static void main(String[] args) {
B ob=new B();
• In this example, we have created the two
packages pack1 and pack2. The A class of pack1 ob.msg();
package is public, so can be accessed from }
outside the package. But msg() method of this }
class is declared as protected, so it can be
accessed from outside the class only through Output
inheritance. Hello
Packages – Access Protection
//save by A.java
package pack1;
public class A {
Public public void msg()
{
• The public access modifier is System.out.println("Hello");
accessible everywhere. }
}
• It has the widest scope among all //save by B.java
other modifiers. package pack2;
• Example of public access modifier import pack1.A;
public class B {
public static void main(String[] args) {
A ob=new A();
ob.msg();
}
}

Output
Hello

You might also like