Package and Polymorphism
Package and Polymorphism
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in
the Java Development Environment.
Syntax
import package.name.Class; // Import a single class
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;
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:
Example
Using the Scanner class to get user input:
import java.util.Scanner;
class MyClass {
System.out.println("Enter username");
Hamsha
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
MyPackageClass.java
package mypack;
class MyPackageClass {
System.out.println("This is my package!");
}
Java Polymorphism
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many
classes that are related to each other by inheritance.
Example
class Animal {
Remember from the Inheritance that we use the extends keyword to inherit
from a class.
Now we can create Pig and Dog objects and call the animalSound() method on
both of them:
Example
class Animal {
class Main {
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
W3schools Pathfinder