Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Unit 2- Package

A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better maintainable code. Packages
are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)
 Built-in Packages

 The Java API is a library of prewritten classes, that are free to use, included in the
Java Development Environment.

 The library is divided into packages and classes. Meaning you can either import a
single class (along with its methods and attributes), or a whole package that contain
all the classes that belong to the specified package.

 To use a class or a package from the library, you need to use the import keyword:

 Syntax

 import package.name.Class; // Import a single class

 import package.name.*; // Import the whole package

 Import a Class

 If you find a class you want to use, for example, the Scanner class, which is used to
get user input, write the following code:

 Example

 import java.util.Scanner;

 In the example above, java.util is a package, while Scanner is a class of


the java.util package.

 To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:

 Import a Package

 There are many packages to choose from. In the previous example, we used
the Scanner class from the java.util package. This package also contains date and time
facilities, random-number generator and other utility classes.
 To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the java.util package:

 Example

 import java.util.*;

 User-defined Packages

 To create your own package, you need to understand that Java uses a file system
directory to store them. Just like folders on your computer:

 Example
 └── root
 └── mypack
 └── MyPackageClass.java

 To create a package, use the package keyword:

 MyPackageClass.java

 package mypack;

 class MyPackageClass {

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

 System.out.println("This is my package!");

 }

 }

 Save the file as MyPackageClass.java, and compile it:


 C:\Users\Your Name>javac MyPackageClass.java
 Then compile the package:
 C:\Users\Your Name>javac -d . MyPackageClass.java
 When we compiled the package in the example above, a new folder was created,
called "mypack".
 To run the MyPackageClass.java file, write the following:
 C:\Users\Your Name>java mypack.MyPackageClass
 The output will be:
 This is my package!

Interfaces

Another way to achieve abstraction in Java, is with interfaces.


An interface is a completely "abstract class" that is used to group related methods with
empty bodies:

Example

// interface

interface Animal {

public void animal Sound(); // interface method (does not have a body)

public void run (); // interface method (does not have a body)

To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class:

Example

// Interface

interface Animal {

public void animal Sound (); // interface method (does not have a body)

public void sleep (); // interface method (does not have a body)

// Pig "implements" the Animal interface

class Pig implements Animal {

public void animal Sound () {

// The body of animal Sound() is provided here

System.out.println("The pig says: wee wee");

public void sleep() {

// The body of sleep() is provided here

System.out.println("Zzz");
}

class Main {

public static void main (String [] args) {

Pig my Pig = new Pig (); // Create a Pig object

myPig.animalSound();

myPig.sleep();

 Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
 Interface methods do not have a body - the body is provided by the "implement" class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?

1) To achieve security - hide certain details and only show the important details of an object
(interface).

2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple
interfaces. Note: To implement multiple interfaces, separate them with a comma (see
example below).

Multiple Interfaces

To implement multiple interfaces, separate them with a comma:

Example

interface FirstInterface {

public void myMethod (); // interface method

}
interface SecondInterface {

public void myOtherMethod (); // interface method

class DemoClass implements FirstInterface, SecondInterface {

public void myMethod() {

System.out.println("Some text..");

public void myOtherMethod() {

System.out.println("Some other text...");

class Main {

public static void main (String [] args) {

DemoClass myObj = new DemoClass ();

myObj.myMethod();

myObj.myOtherMethod();

Exception Handling

Access Protection

The protected keyword is an access modifier used for attributes, methods, and constructors,
making them accessible in the same package and subclasses.
Example

The Student subclass accesses a Person class with protected attributes:

class Person {
protected String fname = "John";

protected String lname = "Doe";

protected String email = "john@doe.com";

protected int age = 24;

class Student extends Person {

private int graduationYear = 2018;

public static void main(String[] args) {

Student myObj = new Student();

System.out.println("Name: " + myObj.fname + " " + myObj.lname);

System.out.println("Email: " + myObj.email);

System.out.println("Age: " + myObj.age);

System.out.println("Graduation Year: " + myObj.graduationYear);

Output
Name: John Doe
Email: john@doe.com
Age: 24
Graduation Year: 2018
Exception Handling- Types,

When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).

Java try and catch

The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.

The try and catch keywords come in pairs:

Syntax

try {

// Block of code to try

catch(Exception e) {

// Block of code to handle errors

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {

public static void main(String[ ] args) {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]); // error!

The output will be something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10


at Main.main(Main.java:4)

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:

Example

public class Main {

public static void main(String[ ] args) {

try {

int[] myNumbers = {1, 2, 3};


System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

The output will be:

Something went wrong.

Throw and Finally statements.


Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

Example

public class Main {

public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

} finally {

System.out.println("The 'try catch' is finished.");

}
The output will be:

Something went wrong.


The 'try catch' is finished.
The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many exception
types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, Sec
urityException, etc:

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":

public class Main {

static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Access denied - You must be at least 18 years old.");

else {

System.out.println("Access granted - You are old enough!");

public static void main(String[] args) {

checkAge(15); // Set age to 15 (which is below 18...)

The output will be:


Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at
least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)

If age was 20, you would not get an exception:

Example

checkage(20);

The output will be:

Access granted - You are old enough

You might also like