OBJECT-ORIENTED PROGRAMMING...Packages A java package is a group of similar types of classes,...
Transcript of OBJECT-ORIENTED PROGRAMMING...Packages A java package is a group of similar types of classes,...
OBJECT-ORIENTED PROGRAMMINGLECTURE # 30
Content
Interfaces
Packages
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is the blueprint of the class.
Interfaces specify what a class must do and not how.
If a class implements an interface and does not provide method bodies for all the abstract functions specified in the interface, then class must be declared abstract.
It cannot be instantiated just like the abstract class.
Interfaces Contd.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface
Interfaces – Syntax and Example
Implementing an Interface
A class definition may, in addition to whatever else it does, implement one or more interfaces.
Once a class states that it implements an interface, it must supply all the methods defined for that interface, complete with executable code.
To implement an interface:
Add implements keyword with the interface-name to the class declaration.
Add the methods specified by the interface to the body of the class.
Implementing an Interface - Example
Relationship between classes and interfaces
Example – Implementing multiple interfaces
Example – Extend an Interface
JAVA 8 Default and JAVA 9 Private Method - Example
Packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
The package keyword is used to create a package in java.
Advantages of Packages
Java package is used to categorize the classes and interfaces so that they can be easily maintained.
Java package provides access protection.
Java package removes naming collision.
Java Packages
Example
Compile the program as follows to create the class file in the defined package. This will create a package “mypack” and Simple.class file in it
For this example,javac -d . Simple.java
To run the program, use the following command
java mypack.simple
Accessing package in another Package
Import the package in your class as shown in the following example