0% found this document useful (0 votes)
8 views

Module 2 (Interfaces and Packages)

Uploaded by

amogh.patadi
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)
8 views

Module 2 (Interfaces and Packages)

Uploaded by

amogh.patadi
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/ 51

Module 2:

Interfaces and Packages


ABSTRACT CLASSES

abstract class A {
final class A { public final void
public abstract void methodOne() {}
methodOne(); }
}
• However, an abstract class can
Clearly, this implementation is invalid have a final method. This final
because a final class cannot have an method is treated like a normal
abstract method. As a final class method with a body which cannot
be overridden.
cannot be inherited.
ABSTRACT CLASSES

• To declare an abstract method, use this general form:


• abstract type name(parameter-list);

• In abstract method, no method body is present.


• Any class that contains one or more abstract methods must also be declared abstract. To declare a
class abstract, you simply use the abstract keyword in front of the class keyword at the beginning
of the class declaration.
• There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator.
• Also, you cannot declare abstract constructors, or abstract static methods.
• Any subclass of an abstract class must either implement all of the abstract methods in the
superclass, or be itself declared abstract.
INTERFACES
• The interface in Java is a mechanism to achieve abstraction.
There can be only abstract methods in the Java interface, not
the method body. It is used to achieve abstraction and multiple
inheritances in Java using Interface. In other words, you can say
that interfaces can have abstract methods and variables. It
cannot have a method body. Java Interface also represents the
IS-A relationship.
• Interfaces are syntactically similar to classes, but they lack instance variables, and their methods
are declared without any body.
DEFINING AN INTERFACE

access interface name {


return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
INTERFACES

• Here, access is either public or not used. When no access specifier is included, then default access
results, and the interface is only available to other members of the package in which it is declared.
• When it is declared as public, the interface can be used by any other code. name is the name of the
interface, and can be any valid identifier.
• Notice that the methods which are declared have no bodies. They end with a semicolon after the
parameter list. They are, essentially, abstract methods; there can be no default implementation of any
method specified within an interface. Each class that includes an interface must implement all of the
methods.
• Variables can be declared inside of interface declarations. They are implicitly final and static, meaning
they cannot be changed by the implementing class. They must also be initialized with a constant value.
All methods and variables are implicitly public if the interface, itself, is declared as public.
Implementing Interfaces

• Once an interface has been defined, one or more classes can implement that interface.
• To implement an interface, include the implements clause in a class definition, and then create the
methods defined by the interface. The general form of a class that
• includes the implements clause looks like this:
• access class classname [extends superclass]
• [implements interface [,interface...]] {
• // class-body
• }
• Here, 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. \
• The methods that implement an interface must be declared public. Also, the type signature of the
implementing method must match exactly the type signature specified in the interface definition.
• // Interface
• interface Animal {
• void sound(); // Abstract method
• void eat(); // Another abstract method
• }

• // Concrete class implementing the interface


• class Dog implements Animal {
• // Implementing methods defined in the interface
• public void sound() {
• System.out.println("Woof");
• }

• public void eat() {


• System.out.println("Eating bones");
• }
• }
• // Another concrete class public class Main {
implementing the interface public static void main(String[] args) {
• class Cat implements Animal { // Creating objects of concrete classes
Dog dog = new Dog();
• // Implementing methods Cat cat = new Cat();
defined in the interface
// Calling methods declared in the interface
• public void sound() { dog.sound();
• System.out.println("Meow"); dog.eat();
cat.sound();
• } cat.eat();
}
}
• public void eat() {
• System.out.println("Eating
fish");
• }
•}
ANOTHER EXAMPLE OF INTERFACES(Accessing Implementations
Through Interface References)

• interface Bank111{ • class Bank{


• float rateOfInterest(); • public static void main(String[] args){
• } • Bank111 b=new SBI();
• class SBI implements Bank111{ • Bank111 p=new PNB();
• public float rateOfInterest(){return 9.15f;} • //SBI sbi1= new SBI();
• } • //PNB pnb1= new PNB();
• class PNB implements Bank111{ • System.out.println("ROI:
• public float rateOfInterest(){return 9.7f;} "+b.rateOfInterest());
• } • System.out.println("ROI:
"+p.rateOfInterest());

• }}
• Notice that variable b is declared to be of the interface type Bank111, yet it
was assigned an instance of SBI class. Although b can be used to access
the rateOfInterest() method, it cannot access any other members of the
SBI class(had it been defined). An interface reference variable only has
knowledge of the methods declared by its interface declaration.
• Thus, b could not be used to access any concrete methods defined
under SBI class(if there are any)
Difference Between Abstract Class and Interface
Difference
Between Abstract
Class and Interface
Multiple inheritance in Java by interface

• If a class implements multiple interfaces, or an


interface extends multiple interfaces, it is known as
multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
Extending Java Interfaces

• An interface can extend another interface in the same


way that a class can extend another class.
The extends keyword is used to extend an interface,
and the child interface inherits the methods of the
parent interface.
• // Filename: Sports.java • // Filename: Hockey.java
• public interface Sports { • public interface Hockey extends Sports {
• public void setHomeTeam(String name); • public void homeGoalScored();
• public void setVisitingTeam(String name); • public void visitingGoalScored();
• } • public void endOfPeriod(int period);
• public void overtimePeriod(int ot);
• // Filename: Football.java • }
• public interface Football extends Sports {
• public void homeTeamScored(int points);
• public void visitingTeamScored(int points);
• public void endOfQuarter(int quarter);
• }
• public class HockeyDemo • public void endOfPeriod(int period)
{}
implements Hockey {
• public void overtimePeriod(int ot)
• public void setHomeTeam(String {}
name) {
• public static void main(String[]
• System.out.println("Home args) {
team: " + name); • Hockey hockeyDemo = new
• } HockeyDemo();

hockeyDemo.setHomeTeam("India");
• public void • }
setVisitingTeam(String name) {} •}

• public void homeGoalScored() {}


Extending Multiple Java Interfaces

• A Java class can only extend one parent class. Multiple


inheritance is not allowed. Interfaces are not classes,
however, and an interface can extend more than one
parent interface.
• The extends keyword is used once, and the parent
interfaces are declared in a comma-separated list.
interface Sports { public class HockeyDemo implements Hockey, Event {
public void setHomeTeam(String name);
public void setVisitingTeam(String name); public void setHomeTeam(String name) {
} System.out.println("Home team: " + name);
}
interface Football extends Sports {
public void homeTeamScored(int points); public void setVisitingTeam(String name) {}
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter); public void homeGoalScored() {}
}
public void visitingGoalScored() {}
interface Hockey extends Sports {
public void homeGoalScored(); public void endOfPeriod(int period) {}
public void visitingGoalScored();
public void endOfPeriod(int period); public void overtimePeriod(int ot) {}
public void overtimePeriod(int ot);
}
interface Event { public void organize() {
public void organize(); System.out.println("Match organized. ");
} }
• public static void main(String[] args) {
• HockeyDemo hD = new HockeyDemo();
• hD.setHomeTeam("India");
• hD.organize();
• }
•}
Access Protection in Java Packages
In java, the access modifiers define the accessibility of the class and its members. For example, private members are accessible within
the same class members only. Java has four access modifiers, and they are default, private, protected, and public.
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The class acts as a container of data and
methods. So, the access modifier decides the accessibility of class members across the different packages.
In java, the accessibility of the members of a class or interface depends on its access specifiers. The following table provides
information about the visibility of both data members and methods.
ACCESS MODIFIERS
1.Private: The access level of a private modifier is only within the
class. It cannot be accessed from outside the class.
2.Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If
you do not specify any access level, it will be the default.
3.Protected: The access level of a protected modifier is within
the package and outside the package through child class. If you
do not make the child class, it cannot be accessed from outside
the package.
4.Public: The access level of a public modifier is everywhere. It
can be accessed from within the class, outside the class, within
the package and outside the package.
PRIVATE ACCESS MODIFIER
1.class A{
2.private int data=40;
3.private void msg(){System.out.println("Hello java");}
4.}
5.
6.public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12.}
Private Constructor

1.class A{
2.private A(){}//private constructor
If you make any class
3.void msg(){System.out.println("Hello java");}
4.} constructor private, you
5.public class Simple{ cannot create the
6. public static void main(String args[]){instance of that class
from outside the class.
7. A obj=new A();//Compile Time Error
8. }
9.}
PROTECTED ACCESS MODIFIER
• The protected access modifier is accessible within
package and outside the package but through
inheritance only.
• The protected access modifier can be applied on the
data member, method and constructor. It can't be
applied on the class.
PROTECTED ACCESS MODIFIER
/save by A.java
package pack;
package mypack;
public class A{ import pack.*;
protected void msg(){System.out.pr
intln("Hello");}
class B extends A{
} public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.
There are two types of binding
1.Static Binding (also known as Early Binding).
2.Dynamic Binding (also known as Late Binding).

static binding
When type of the object is determined at compiled time(by the compiler), it is
known as static binding.
If there is any private, final or static method in a class, there is static binding.

Dynamic binding
When type of the object is determined at run-time, it is
known as dynamic binding.
Java ‘instanceof’ Operator
The instanceof operator in Java is used to check whether an object is an instance of a particular class
or not.
Its syntax is
objectName instanceOf
Here, if objectName className;
is an instance of className, the operator returns true. Otherwise, it returns false.
JAVA PACKAGES

• In java, a package is a container of classes, interfaces, and


sub-packages. We may think of it as a folder in a file directory.

• We use the packages to avoid naming conflicts and to organize


project-related classes, interfaces, and sub-packages into a
bundle.

• In java, the packages have divided into two types.


• Built-in Packages

• User-defined Packages
JAVA PACKAGES
• Built-in Packages

• The built-in packages are the packages from java API. The Java API is a library of pre-defined classes, interfaces, and
sub-packages. The built-in packages were included in the JDK.

• There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax, swing, net, sql, etc.

• We need to import the built-in packages to use them in our program.

• Thus, the library is divided into packages and classes. Meaning you can
either import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
• User-defined Packages

• The user-defined packages are the packages created by the user. User is free to create their own packages.
Defining a Package in java

• We use the package keyword to create or define a package in java programming language.

• Syntax:

• package packageName;
Using a package from library using import

To use a class or a package from the library, you need to use the import keyword:

import package.name.Class; // Import a single class


import package.name.*; // Import the whole package
Import a class in java

import java.util.Scanner;
class MyClass
{ public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
In the example, java.util is a
System.out.println("Enter username"); package, while Scanner is a class
String userName = myObj.nextLine(); of the java.util package.
System.out.println("Username is: " +
userName);
} }
Importing all the classes

• Using an importing statement, we can import all the classes of a


package. To import all the classes of the package, we use *
symbol. The following syntax is employed to import all the
classes of a package.
• Syntax
• import packageName.*;
• Let's look at an import statement to import a built-in package.
Importing all the classes

• package myPackage;
• import java.util.*;
• public class ImportingExample
• {
• public static void main(String[] args)
• {
• Scanner read = new Scanner(System.in);
• int i = read.nextInt();
• System.out.println("You have entered a number " + i);
• Random rand = new Random();
• int num = rand.nextInt(100);
• System.out.println("Randomly generated number " + num);
• }
• }
Importing all the classes

• In the above code, the class ImportingExample belongs to myPackage package, and it also
importing all the classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from
the java.util package.
• 🔔 The import statement imports only classes of the package, but not sub-packages and its classes.
• We may also import sub-packages by using a symbol '.' (dot) to separate parent package and sub-
package.
• Consider the following import statement.

import java.util.*;
• The above import statement util is a sub-package of java package. It imports all the classes
of util package only, but not classes of java package.
How to access package from another
package?

• The ways to access the package from outside the


package-
1.import package.*;
2.import package.classname;
3.Using fully qualified name
Using packagename.*

• If you use package.* then all the classes and interfaces of this package w

• The import keyword is used to make the classes and interface of anothe
EXAMPLE

//save by A.java
//save by B.java
package pack;
package mypack;
public class A{ import pack.*;
public void msg(){System.out.
println("Hello");} class B{
} public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using packagename.classname

If you import package.classname then only declared class of this package will
be accessible.
/save by B.java
//save by A.java package mypack;
package pack; import pack.A;
public class A{
public void msg(){System.out.println("Hello");}
class B{
} public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using fully qualified name

• If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. But
you need to use fully qualified name every time when you are
accessing the class or interface.
Using fully qualified name
//save by A.java
package pack;
//save by B.java
public class A{
package mypack;
public void msg(){System.out
.println("Hello");} class B{
public static void main(String args
} []){
pack.A obj = new pack.A();//using fu
lly

qualified name
obj.msg();
NOTE
• If you import a package, all the classes and interface of that
package will be imported excluding the classes and interfaces
of the subpackages. Hence, you need to import the subpackage
as well.
TASK 2
• Write a Java program to create a class called Shape with a
method called getArea(). Create a subclass called Rectangle
that overrides the getArea() method to calculate the area of a
rectangle.

You might also like