Packages and Interfaces Chapter 04 PDF
Document Details
Uploaded by FineEnlightenment390
Wachemo University College of Natural and Computational Science
Tags
Summary
This document is a chapter on packages and interfaces in Java programming. It covers creating packages, importing packages, access protection, creating and using interfaces, and includes examples of implementation.
Full Transcript
Packages and Interfaces Chapter 04 Objectives After studying this chapter, students should be able to learn: Packages – Creating a Package – Importing a Package – Access Protection Interfaces – Creating an interface – Using an i...
Packages and Interfaces Chapter 04 Objectives After studying this chapter, students should be able to learn: Packages – Creating a Package – Importing a Package – Access Protection Interfaces – Creating an interface – Using an interface 2 Introduction A package is a container of classes and interfaces. A package represents a directory that contains related group of classes and interfaces. For example, when we write statements like: import java.io.*; – Here we are importing classes of java.io package. – Here, java is a directory name and io is another sub directory within it. – The ‘*’ represents all the classes and interfaces of that io sub directory. We can create our own packages called User-defined packages or extend the available packages, called Built-in packages. User-defined packages can also be imported into other classes and used exactly in the same way as the built-in packages. Packages provide reusability. 3 Creating a Package Syntax for creating a package: package packagename; Ex: package pack; The package creation statement must be the first statement in the program while creating a package. Declare all the members and the class itself as public – then only the public members are available outside the package to other programs. When the package statement is omitted, class names are put into the default package which has no name. 4 Package Hierarchy To create a package hierarchy, separate each package name with a dot: package myPackage1.myPackage2.myPacka ge3; A package hierarchy must be stored accordingly in the file system: myPackage1\myPackage2\myPackage3 You cannot rename a package without renaming its directory! 5 Example – Creating a Package //creating a package package pack; public class Addition { private double d1,d2; public Addition(double a,double b) { d1 = a; d2 = b; } public void sum() { System.out.println ("Sum of given numbers is :" + (d1+d2) ); } } Compile: D:\JQR\javac –d. Addition.java The –d option tells the Java compiler to create a separate directory and place the.class file in that directory (package). The (.) dot after –d indicates that the package should be created in the current directory. 6 Accessing a Package As packages are stored in directories, how does the Java run-time system know where to look for packages? Two ways: 1. The current directory is the default start point - if packages are stored in the current directory or sub-directories, they will be found. 2. Specify a directory path or paths by setting the CLASSPATH environment variable. 7 CLASSPATH Variable CLASSPATH - environment variable that points to the root directory of the system’s package hierarchy. Several root directories may be specified in CLASSPATH. Java will search for the required packages by looking up subsequent directories described in the CLASSPATH variable. 8 Importing of Packages Since classes within packages must be fully- qualified with their package names, it would be tedious to always type long dot-separated names. The import statement allows to use classes or whole packages directly. Importing of a concrete class: import myPackage1.myPackage2.myClass; Importing of all classes within a package: import myPackage1.myPackage2.*; The import statement occurs immediately after the package statement and before the class statement. 9 Example – Importing a Package //Using the package pack import pack.Addition; class Use { public static void main(String args[]) { Addition ob1 = new Addition(10,20); ob1.sum(); } } 10 Example- Adding a one more class to package //Adding one more class to package pack: package pack; public class Subtraction { private double d1,d2; public Subtraction(double a, double b) { d1 = a; d2 = b; } public void difference() { System.out.println("Subtraction: " + (d1 - d2)); } } 11 Example – Importing all classes //To import all the classes and interfaces in a class using import pack.*; import pack.*; class Use { public static void main(String args[]) { Addition ob1 = new Addition(10.5,20.6); ob1.sum(); Subtraction ob2 = new Subtraction(30.2,40.11); ob2.difference(); } } 12 Creating sub package We can create sub package in a package in the format: package packagename.subpackagename; Ex: package pack1.pack2; Here, we are creating pack2 subpackage which is created inside pack1 package. To use the classes and interfaces of pack2, we can write import statement as: import pack1.pack2; //Creating a subpackage in a package package pack1.pack2; public class Sample { public void show () { System.out.println ("Hello Java Learners"); } } 13 Access Protection Specifies the scope of the data members, class and methods. – private members of the class are available with in the class only. The scope of private members of the class is “CLASS SCOPE”. – public members of the class are available anywhere. The scope of public members of the class is "GLOBAL SCOPE". – default members of the class are available with in the class, outside the class and in its sub class of same package. It is not available outside the package. So the scope of default members of the class is "PACKAGE SCOPE". – protected members of the class are available with in the class, outside the class and in its sub class of same package and also available to subclasses in different package also. 14 Access Specifiers - Example //class A with different access specifiers package same; public class A //class B of same package, access the { private int a=1; variables public int b = 2; package same; import same.A; protected int c = 3; public class B int d = 4; { } public static void main(String args[]) { A obj = new A(); System.out.println(obj.a); System.out.println(obj.b); System.out.println(obj.c); System.out.println(obj.d); } } 15 Contd. package another; import same.A; public class C extends A { public static void main(String args[]) { C obj = new C(); System.out.println(obj.a); System.out.println(obj.b); System.out.println(obj.c); System.out.println(obj.d); } } 16 Interface A programmer uses an abstract class when there are some common features shared by all the objects. A programmer writes an interface when all the features have different implementations for different objects. Interfaces are written when the programmer wants to leave the implementation to third party vendors. An interface is a specification of method prototypes. An interface contains zero or more abstract methods and all the methods of interface are public, abstract by default. 17 Contd. An interface may contain variables which are by default public static final. Once an interface is written any third party vendor can implement it. All the methods of the interface should be implemented in its implementation classes. If any one of the method is not implemented, then that implementation class should be declared as abstract. We cannot create an object to an interface. We can create a reference variable to an interface. An interface cannot implement another interface. An interface can extend another interface. A class can implement multiple interfaces. 18 Defining an Interface access-specifier interface-name { type final-varname1 = value; type final-varname2 = value;... return-type method-name1(parameter-list); return-type method-name2(parameter-list);... } Access can be public or default The methods which are declared have no bodies(abstract). They end with a semicolon after the parameter list. Each class that includes an interface must implement all of the methods. 19 Contd. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface access class classname [extends superclass][implements interface [,interface...]] { // class-body } access is either public or not used. If a class implements more than one interface , the interfaces are separated with a comma. If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface. 20 Example - Interface interface Shape { void area (); void volume (); double pi = 3.14; } class Circle implements Shape { double r; Circle (double radius) { r = radius; } public void area () { System.out.println("Area of a circle is:" + pi*r*r ); } public void volume () { System.out.println("Volume of a circle is:" + 2*pi*r); } } 21 class Rectangle implements Shape { double l,b; Rectangle (double length, double breadth) { l = length; b = breadth; } public void area () { System.out.println("Area of a Rectangle is: " + l*b ); } public void volume () { System.out.println("Volume of a Rectangle is:"+2*(l+b)); } } class InterfaceDemo { public static void main (String args[]) { Circle ob1 = new Circle (10.2); ob1.area (); ob1.volume (); Rectangle ob2 = new Rectangle (12.6, 23.55); ob2.area (); ob2.volume (); } } 22 Multiple Inheritance Java does not support multiple inheritance. But it can be achieved by using interfaces. interface Father { double PROPERTY = 10000; double HEIGHT = 5.6; } interface Mother { double PROPERTY = 30000; double HEIGHT = 5.4; } class MyClass implements Father, Mother { void show() { System.out.println("Total property is:" + (Father.PROPERTY+Mother.PROPERTY)); System.out.println("Average height is:"+ (Father.HEIGHT+ Mother.HEIGHT)/2); } } 23 Contd. class InterfaceDemo { public static void main(String args[]) { MyClass ob1 = new MyClass(); ob1.show(); } } 24 Some of Java's Most used Interfaces Iterator – To run through a collection of objects without knowing how the objects are stored, e.g., in array, list, bag, or set. Cloneable – To make a copy of an existing object via the clone() method on the class Object. Serializable – Pack a web of objects such that it can be send over a network or stored to disk. An naturally later be restored as a web of objects. – More on this in the lecture on Java's I/O system Comparable – To make a total order on objects, e.g., 3, 56, 67, 879, 3422, 34234 25 Interface vs. Abstract Class Interface Abstract Class Methods can be declared Methods can be declared No method bodies Method bodies can be defined “Constants” can be declared All types of variables can be declared Has no constructors Can have constructors Multiple inheritance possible Multiple inheritance not Has no top interface possible Multiple “parent” interfaces Always inherits from Object Only one “parent” class 26 Self -Review Questions 1. What is a package? How do we design a package? 2. How do we add a class or interface to a package? 3. Explain in detail about accessing a package. 4. Explain about the access protection in packages? 5. What is interface? Write a program to demonstrate how interfaces can be extended. 6. Does Java Support multiple inheritance? Write Java a program to implement the multilevel Inheritance. 27 THANK YOU 28