Showing posts with label Cloneable. Show all posts
Showing posts with label Cloneable. Show all posts

Saturday, 1 June 2019

Why a collection doesn’t extend Cloneable or Serializable interfaces?


When you see the definition of Collection interface, it is defined like below.

public interface Collection<E> extends Iterable<E> {
    .....
    .....
}

As you see Collection interface doesn’t extend Cloneable or Serializable interface.

Why Collection interface doesn’t extend Cloneable or Serializable interfaces?
It is because, Collection is the root interface for all the collection classes (like ArrayList, LinkedList). If collection interface extends Cloneable/Serializable interfaces, then it is mandating all the concrete implementations of this interface to implement cloneable and serializable interfaces. To give freedom to concrete implementation classes, Collection interface don’t extended Cloneable or Serializable interfaces.



You may like

Monday, 17 February 2014

Interface extends Other interface

In Java, one interface can extends other interface.

Syntax
   interface Interface2 extends Interface1{

   }

Example
interface Interface1{
 int sum(int a, int b);
}

interface Interface2 extends Interface1{
 int sum(int a, int b, int c);
}


Any class implementing the interface “Interface2” must provide the implementation for both the methods
   int sum(int a, int b);
   int sum(int a, int b, int c);

class Sum implements Interface2{
 public int sum(int a, int b, int c){
  return (a+b+c);
 }
}
When you tries to compile the above program, compiler throws the below error.

Sum.java:1: error: Sum is not abstract and does not override abstract method sum(int,int) in Interface1
class Sum implements Interface2{
^
1 error

To make the program compiles fine, implement both the methods.
class Sum implements Interface2{
 public int sum(int a, int b, int c){
  return (a+b+c);
 }

 public int sum(int a, int b){
  return (a+b);
 }
}

Some Points to Remember
1. Can an Interface abstract ?
Yes, but no point in putting abstract modifier for the interface, since all the method in interface are abstract by default

Example
    abstract interface Area{
        double PI=3.1428;
        double getArea(double r);
    }

2. Can an interface extend more than one interface ?
A single interface can extend any number of other interfaces.
  
Example
interface Interface1{
 int sum(int a, int b);
}

interface Interface2 extends Interface1{
 int sum(int a, int b, int c);
}


interface Interface3 extends Interface1, Interface2{

}

3. Is empty interface like below are valid ?
Interface Interface1{

}

Yes, It is Perfectly valid. Interfaces without methods and fields are called marker interfaces. Serializable, Cloneable and Remote interfaces are marker interfaces.
         

Implement more than one interface                                                 Class inside interface                                                 Home