packages
TRANSCRIPT
Packages and Interfaces
Package - is a collection of related classes and interfaces that provides access protection and namespace management.
Packages
Declare the package at the beginning of a file using the form:
package packagename;
Example: package firstPackage; Public class FirstClass {
//Body of the class }
Creating a package
Two types of packages:
1. Java API packages 2. User defined packages
Types of packages
The general form of importing package is:
import packagename.classname;or
import Packagename.*;
Example:
import myPackage.ClassA; import myPackage.secondPackage .ClassName; import myPackage.*;
Importing a package
Public : available/visible everywhere
Private : only visible within that class
Protected : visible every where except the non-subclasses in other package
Visibility Modifiers
Visibility Modifier Table
package pack;class c2 { void show_c2() { System.out.println("show_c2"); } }public class c1 extends c2 { public void show_c1() { System.out.println("show_c1"); show_c2(); } }
Hiding Classes
import pack.c1;class dmn_pack { public static void main(String ar[]) { c1 c=new c1(); c.show_c1(); }}
Cont…..
Interface
It defines a standard and public way of specifying the behavior of classes.
It supports the concept of multiple inheritance.
All methods of an interface are abstract methods.
To define an interface, we write:
interface Interface Name [extends other interfaces] { constant declarations ; abstract method declarations ; }
How we define Interface?
Example: interface Animal { int a =10; public void eat( ); public void travel( ); }
Example of Interface
Once an interface has been defined, one or more classes can implement that interface.
This can be done as:
Class classname implements interfacename { body of classname }
Implementing Interfaces
public class Mammal implements Animal { public void eat() { System.out.println ("Mammal eats"); } public void travel() { System.out.println ("Mammal travels"); } public static void main(String args[ ]) { Mammal m = new Mammal( ); m.eat(); m.travel(); } }
Example of Interface
An interface can extend another interface, similarly to the way that a class can extend another class.
The extends keyword is used to extend an interface.
Syntax:
interface name2 extends name1 { body of name2 }
Extending Interfaces
Difference between Interface & Class ???
Practical Example