0% found this document useful (0 votes)
26 views17 pages

5 - Packages and Interface

The document discusses abstract classes and interfaces in Java. It defines abstract classes and interfaces, describes how to create abstract methods and classes, and compares the differences between abstract classes and interfaces. It also covers packages in Java and how they are used to organize classes and control access/visibility.

Uploaded by

gourilakshmis78
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views17 pages

5 - Packages and Interface

The document discusses abstract classes and interfaces in Java. It defines abstract classes and interfaces, describes how to create abstract methods and classes, and compares the differences between abstract classes and interfaces. It also covers packages in Java and how they are used to organize classes and control access/visibility.

Uploaded by

gourilakshmis78
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

14-02-2024

Abstract class and Interfaces

14-Feb-24

Abstract Class and Interface


 Definitions
 abstract methods = Methods that are declared, with no
implementation
 abstract class = A class with abstract methods, not meant to
be instantiated
 interface = A named collection of method definitions
(without implementations)

1
14-02-2024

Abstract Class
 An abstract class cannot be instantiated, but other
classes are derived from it.
 An Abstract class serves as a superclass for other
classes.
 The abstract class represents the generic or abstract
form of all the classes that are derived from it.
 A class becomes abstract when you place the abstract
key word in the class definition.

public abstract class ClassName

Abstract Method
 An abstract method has no body and must be overridden in a
subclass.
 An abstract method is a method that appears in a superclass,
but expects to be overridden in a subclass.
 Notice that the key word abstract appears in the header, and
that the header ends with a semicolon.
public abstract void setValue(int value);
 Any class that contains an abstract method is automatically
abstract.
 If a subclass fails to override an abstract method, a compiler error will
result.
 Abstract methods are used to ensure that a subclass implements the
method.

2
14-02-2024

Abstract Class
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}

Interface
 An interface is a contract between its producer and client
 The general format of an interface definition:
public interface InterfaceName
{
//(Method headers...)
}
 All methods specified by an interface are public by default.
 A class (as a producer) can implement one or more interfaces.
 If a class implements an interface, it uses the implements
keyword in the class header.
public class person implements athelete
{
// must implement all amethods in the Interface
}

3
14-02-2024

Interface
 An interface can contain field declarations:
 all fields in an interface are treated as final and static.

 To specify multiple interfaces in a class definition, simply list


the names of the interfaces, separated by commas, after the
implements key word.
public class MyClass implements
Interface1,Interface2, Interface3

Interface
interface Singer {
void sing();
void warmUpVoice();
}

interface Dancer {
void dance();
void stretchLegs();
}

interface Talented extends Singer, Dancer {

// can sing and dance.


void sing(){}
void warmUpVoice(){}
void dance(){}
void stretchLegs(){}

4
14-02-2024

Difference
 An interface cannot implement any methods, whereas
an abstract class can
 A class can implement many interfaces but can have
only one superclass (abstract or not)
 An interface is not part of the class hierarchy.
Unrelated classes can implement the same interface

Abstract class vs Interface


 Abstract class is declared with  An interface is treated like a special
abstract keyword class in Java. Each interface is
 It can have abstract and non- compiled into a separate bytecode
abstract methods file, just like a regular class
 Abstract Method contains no  Can not create instance from an
implementation, i.e. no body. interface using the new operator
 Abstract Method is created to force  Can be used as a data type for a
same name and signature pattern in reference variable
all the subclasses  Relationship between the class and
 Subclasses have the flexibility to the interface is known as interface
code these methods with their own inheritance
specific requirements  All data fields are public final static
 An abstract method cannot be and all methods are public abstract
contained in a non-abstract class in an interface, Java allows these
modifiers to be omitted.

5
14-02-2024

Abstract class vs Interfaces

Abstract class vs Interfaces

6
14-02-2024

Packages and Interfaces

14-Feb-24

Packages and Interfaces


 Two of Java’s most innovative features:
 packages and interfaces

14

7
14-02-2024

Packages
 In general, a unique name had to be used for each class to
avoid name collisions
 After a while, without some way to manage the name
space, you could run out of convenient, descriptive names
for individual classes.
 Java provides a mechanism for partitioning the class name
space into more manageable chunks. - Package
 A package in Java is used to group related classes.
 Think of it as a folder in a file directory. We use packages
to avoid name conflicts, and to write a better
maintainable code.
 The package is both a naming and a visibility control
mechanism. --- HOW??
15

Uses
 Packages are used for:
 A Preventing naming conflicts.
 For example there can be two classes with name

Employee in two packages,


 college.staff.cse.Employee and

college.staff.ee.Employee
 Providing controlled access:
 protected and default have package level access

control. A protected member is accessible by classes in


the same package and its subclasses. A default member
(without any access specifier) is accessible by classes
in the same package only.

16

8
14-02-2024

Defining a Package
 To create a package simply include a package command
as the first statement in a Java source file.
 Any classes declared within that file will belong to the
specified package.
 The package statement defines a name space in which
classes are stored.
 If you omit the package statement, the class names are
put into the default package, which has no name.

17

Defining a Package

C:\Users\Your Name>javac -d . Package_Ex.java


C:\Users\Your Name>java mypack.Package_Ex

To execute, class name must be qualified with its package name.

18

9
14-02-2024

Defining a Package
 This forces the compiler to create the "mypack" package.

 The -d keyword specifies the destination for where to


save the class file.
 You can use any directory name, like c:/user (windows),
or, if you want to keep the package within the same
directory, you can use the dot sign ".", like in the example
above.

 Note: The package name should be written in lower case


to avoid conflict with class names.

Access Protection
 Classes and packages are both means of encapsulating and
containing the name space and scope of variables and
methods.
 Classes act as containers for data and code.
 The class is Java’s smallest unit of abstraction.
 Packages act as containers for classes and other
subordinate packages.
 Java addresses four categories of visibility for class
members:
 Subclasses in the same package
 Non-subclasses in the same package
 Subclasses in different packages
 Classes that are neither in the same package nor subclasses

10
14-02-2024

Access Protection
 Public - Anything declared public can be accessed from
anywhere.
 Private - Anything declared private cannot be seen outside
of its class.
 Package - When a member does not have an explicit
access specification, it is visible to subclasses as well as to
other classes in the same package. - This is the default
access.
 Protected - If you want to allow an element to be seen
outside your current package, but only to classes that
subclass your class directly

Access Protection

11
14-02-2024

Access within Same Package

Demo

Access from other Package


 Importing Packages
 Java includes the import statement to bring certain
classes, or entire packages, into visibility.
 Once imported, a class can be referred to directly, using
only its name.
 In a Java source file, import statements occur
immediately following the package statement (if it exists)
and before any class definitions.
 This is the general form of the import statement:

12
14-02-2024

Access from other Package


 pkg1 is the name of a top-level package, and pkg2 is the
name of a subordinate package inside the outer package
separated by a dot (.).
 There is no practical limit on the depth of a package
hierarchy.
 Finally, you specify either an explicit classname or a star
(*), which indicates that the Java compiler should import
the entire package.
 This code fragment shows both forms in use:

Accessing Classes in a Package


 Fully Qualified class name:
Example:
java.util.Scanner s=new java.util.Scanner(System.in);

 import packagename.classname;
Example: import java.util. Scanner;
or
import packagename.*;
Example: import java.util.*;

Import statement must appear at the top of the file, before


any class declaration.

13
14-02-2024

Info bits!!!!
 The star form may increase compilation time—especially if you
import several large packages.
 For this reason it is a good idea to explicitly name the classes
that you want to use rather than importing whole packages.
 However, the star form has absolutely no effect on the run-time
performance or size of your classes.
 All of the standard Java classes included with Java are stored in
a package called java.
 The basic language functions are stored in a package inside of
the java package called java.lang.
 Normally, you have to import every package or class that you
want to use, but since Java is useless without much of the
functionality in java.lang, it is implicitly imported by the
compiler for all programs.

Package Types
 Packages are divided into two categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own packages)
 Built-in Packages
 The Java API is a library of prewritten classes, that are free to use,
included in the Java Development Environment.
 The complete list can be found at Oracles website:
https://docs.oracle.com/javase/8/docs/api/.
 User-defined Packages
 These are the packages that are defined by the user.
 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

14
14-02-2024

Example Built-in Packages


 1) java.lang: Contains language support classes(e.g classed
which defines primitive data types, math operations). This
package is automatically imported.
 2) java.io: Contains classed for supporting input / output
operations.
 3) java.util: Contains utility classes which implement data
structures like Linked List, Dictionary and support ; for Date /
Time operations.
 4) java.applet: Contains classes for creating Applets.
 5) java.awt: Contain classes for implementing the components
for graphical user interfaces (like button , ;menus etc).
 6) java.net: Contain classes for supporting networking
operations.

Example1-Package

package p1; import p1.*;


public class ClassA
{ Class testclass
public void displayA( ) {
{ public static void main(String str[])
System.out.println(“Class A”); {
} ClassA obA=new ClassA();
} obA.displayA();
}
}

15
14-02-2024

Example2-Package

package p2; import p1.*;


public class ClassB import p2.*;
{
protected int m =10; class PackageTest2
public void displayB() {
{ public static void main(String str[])
System.out.println(“Class B”); {
System.out.println(“m= “+m); ClassA obA=new ClassA();
} ClassB obB=new ClassB();
} obA.displayA();
obB.displayB();
}
}

Example 3- Package

import p2.ClassB; class PackageTest3


class ClassC extends ClassB {
{ public static void main(String args[])
int n=20; {
void displayC() ClassC obC = new ClassC();
{ obC.displayB();
System.out.println(“Class C”); obC.displayC();
System.out.println(“m= “+m); }
System.out.println(“n= “+n); }
}
}

16
14-02-2024

The End

17

You might also like