packages

19

Click here to load reader

Upload: priyatrehan

Post on 25-May-2015

465 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Packages

Packages and Interfaces

Page 2: Packages

Package - is a collection of related classes and interfaces that provides access protection and namespace management.

Packages

Page 3: 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

Page 4: Packages

Two types of packages:

1. Java API packages 2. User defined packages

Types of packages

Page 5: Packages
Page 6: 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

Page 7: Packages

Public : available/visible everywhere

Private : only visible within that class

Protected : visible every where except the non-subclasses in other package

Visibility Modifiers

Page 8: Packages

Visibility Modifier Table

Page 9: Packages

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

Page 10: Packages

import pack.c1;class dmn_pack { public static void main(String ar[]) { c1 c=new c1(); c.show_c1(); }}

Cont…..

Page 11: Packages

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.

Page 12: Packages

To define an interface, we write:

interface Interface Name [extends other interfaces] { constant declarations ; abstract method declarations ; }

How we define Interface?

Page 13: Packages

Example: interface Animal { int a =10; public void eat( ); public void travel( ); }

Example of Interface

Page 14: Packages

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

Page 15: Packages

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

Page 16: Packages

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

Page 17: Packages

Difference between Interface & Class ???

Page 18: Packages

Practical Example

Page 19: Packages