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

Abstract Class, Interface Package

Uploaded by

shresthasudip574
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Abstract Class, Interface Package

Uploaded by

shresthasudip574
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only essential things to the user and hides the internal details,

Ways to achieve Abstraction


There are two ways to achieve abstraction in java

Abstract class
Interface

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods.

A partially completed/implemented class is known as abstract class. When a class is not


100% completed we can make it an abstract class.

If a class is an abstract class, then we must assume a class is not 100% completed or
implemented. So, someone is responsible to complete/implement the Abstract class.

Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructor & static method also.
It can have final methods which will force the subclass not to change the body of
the method.

Example of abstract class

abstract class A
{
// Abstract & non abstract method
}

Note: There may be Zero number of abstract methods in Abstract class also

Abstract Method in Java


1
A method which is declared as abstract and does not have implementation or doesn’t
have body is known as an abstract method.

Example

Abstract public void printStatus(); //no method body and abstract

If a method is defined without the body in Abstract class, child class is responsible to
implement these methods.

Example of Abstract class that has an abstract method


abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run()
{
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Abstract class having constructor, data member and methods


An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor.

abstract class Bike{


Bike(){
System.out.println("bike is created");
}
abstract void run();
void changeGear(){

2
System.out.println("gear changed");
}
}
class Honda extends Bike{
void run(){
System.out.println("running safely..");
}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

Note: If there is an abstract method in a class, that class must be abstract.

Rule: If you are extending an abstract class that has an abstract method, you must
either provide the implementation of the method or make this class abstract.

Example:

abstract class Test


{
public abstract void m1();
public abstract void m1();
}
Abstract class SubTest1 extends Test
{
Public void m1()
{
System.out.println(“M1 methods running”);
}
}
class SubTest2 extends Test
{
public void m2()

3
{
System.out.println(“M2 methods running”);
}
}
public class TestMain
{
public static void main(String args[])
{

}
}
Interface in Java
The interface in Java is a mechanism to achieve abstraction. An interface is a blue print
of a class which has only abstract method with no body. It is also c an’t be instantiated
like an abstract class.

Any service requirement specification, someone is responsible to provide the


implementation.

Any Contract between client and service provider is called interface.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Since java 8 & 9 version we can’t say interface is a 100% Abstract class.

Why use Java interface?


There are mainly Two reasons to use interface. They are given below.

It is used to achieve abstraction.


By interface, we can support the functionality of multiple inheritance.

Declaration of Interface
interface <interface_name> {
// declare constant fields
// declare methods that public and abstract by default

4
}

Note: The Java compiler adds public and abstract keywords before the interface
method. and, it adds public, static and final keywords before data members.

In other word, Interface fields are public, static and final by default, and the methods
are public and abstract.

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.

interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();

5
obj.print();
}
}
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its implementation is
provided by Rectangle and Circle classes.

interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw(){
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable{
public void draw(){
System.out.println("drawing circle");
}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}
}

Bank
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){
return 9.15f;

6
}
}
class PNB implements Bank{
public float rateOfInterest(){
return 9.7f;
}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}

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");

7
}
public void show(){
System.out.println("Welcome");
}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Interface inheritance
A class implements an interface, but one interface extends another interface.

Java 8 default method in java


interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){
System.out.println("drawing rectangle");
}
}
class TestI nterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}
}
Java 8 static method in java

8
interface Drawable{
void draw();
static int cube(int x){
return x*x*x;
}
}
class Rectangle implements Drawable{
public void draw(){
System.out.println("drawing rectangle");
}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}
}
Q) What is marker or tagged interface?
An interface which has no member is known as a marker or tagged interface, for
example, Serializable, Cloneable, Remote, etc.

public interface Serializable {


}
Difference Between Abstract class & Interface

9
10
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface
achieves fully abstraction (100%).

Abstract class loopholes have different notes

Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package.

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

There are almost 5000+ classes are available in java and each and every class must
be inside some package. So, it is good programming practice to make our class in
some package. It is standard form in java.

Advantage of Java Package


Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

11
Java package provides access protection.
Java package removes naming collision.

How to create a package in java?


The package keyword is used to create a package in java.

Syntax

package package_name;

Eg:-

package com.bishal.patel;

NOTE: The Standard format of package name is in domain naming system in


reverse order. However almost in every books any name is given.

package com.bishal.patel;
public class SimplePackage{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package?
javac -d directory javafilename

12
Example

javac -d . SimplePackage.java

-d means destination, (dot). Means current working directory. This statement creates a
folder in the current working directory with package name.

com->Bishal->patel->SimplePackage.class

you can give any destination at the place of (dot). But usually we give only dot.

How to run java package program?


You need to use fully qualified name e.g. java com.bishal.patel.SimplePackage to run
the class.

To compile: javac –d . SimplePackage.java

To run: java com.bishal.patel.SimplePackage

Two Conslusion be there in the package


package pack1;
package pack1;
public class SimplePackage{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How many .class file will create, where


this .class file will be store. Is it valid or not ?

13
import java.util.Scanner;
package pack1;
public class SimplePackage{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to package");
}
}
Is it valid, if yes then how if no then why?

Modifiers in Java
There are two types of modifiers in java.

Access modifiers.
Non-access modifiers.

In the we focus on access modifiers deeply.

Access Modifiers
The access modifiers in Java specifies the accessibility of a field, method, constructor, or
class.

There are four types of Java access modifiers:

private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
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.
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.
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.

14
There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, final, strictfp etc. Here, we are going to learn the access modifiers
only.

Private

The private access modifier is accessible only within the class.

class A{
private int data=40;
private void msg(){
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Note: If you make any class constructor private, you cannot create the instance of
that class from outside the class. For example:

Private constructor
class A{
private A() //private constructor
{
}
}
public class Simple{
public static void main(String args[]){
A obj=new A(); //Compile Time Error
}
}

15
Note: A class cannot be private or protected except nested class.

Default

If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package.

It provides more accessibility than private. But, it is more restrictive than protected, and
public.

Example

package pack;
class A{
void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}

Protected

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.

It provides more accessibility than the default modifer.

package pack;
public class A{
protected void msg(){
System.out.println("Hello");

16
}
}
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

Modifiers Oute Inner Methods Variabl Outer Inner Constructor


r Class e Interface Interface
Class
public ✔ ✔ ✔ ✔ ✔ ✔ ✔

Private ✖ ✔ ✔ ✔ ✖ ✔ ✔

protected ✖ ✔ ✔ ✔ ✖ ✔ ✔

Default ✔ ✔ ✔ ✔ ✔ ✔ ✔

Final ✔ ✔ ✔ ✔ ✖ ✖ ✖

abstract ✔ ✔ ✔ ✖ ✔ ✔ ✖

Static ✖ ✔ ✔ ✔ ✖ ✔ ✖

17
Synchro ✖ ✖ ✔ ✖ ✖ ✖ ✖

Native ✖ ✖ ✔ ✖ ✖ ✖ ✖

Strictfp ✔ ✔ ✔ ✖ ✔ ✔ ✖

transient ✖ ✖ ✖ ✔ ✖ ✖ ✖

Volatile ✖ ✖ ✖ ✔ ✖ ✖ ✖

Some Important Questions


The modifiers which are applicable for inner classes but not for outer classes.
 private, protected, static
The modifiers which are applicable for classes but not for interface final.
The modifiers which are applicable only for method and which can’t use
anywhere else native.
The only modifiers which are applicable for constructor.
 public, protected, private, default.
The only applicable modifiers for local variable is final.

18
Class A Class A
{ {
Class B static interface B
{ {

} }
} }

interface A interface A
{ {
public static interface B public static Class B
{ {

} }
} }

By default, it should be whether we declare or not.

illegal Combinations of Modifiers


For method

Public ---> private, protected or vice versa

Abstract ---> final, static, private, native, synchronized, strictfp or vice versa

For variable

Public ---> private, protected or vice versa

Final ---> volatile or vice versa

For class

Public ---> private, protected or vice versa

Final ---> abstract or vice versa

19
20

You might also like