Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface with no methods

Why do Java introduces some interface which has no methods defined in it? For example Cloneable, Serializable, Type and many more.

Second thing : In Class.class package there is one method defined registerNatives() without body and is called from static block but Class.class is not abstract but is final. Why so? and Why Java need some method without body to be called from static block.?

like image 494
Vimal Bera Avatar asked Jan 02 '14 07:01

Vimal Bera


People also ask

Can an interface have no methods?

Yes, you can write an interface without any methods. These are known as marking interfaces or, tagging interfaces. A marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented.

What is an interface with no fields or methods?

Explanation: A marker interface is an interface with no fields and methods. In other words, an empty interface (contains nothing) is known as the marker interface.

Why marker interface has no methods?

Marker Interfaces in Java have special significance because of the fact that they have no methods declared in them which means that the classes implementing these interfaces don't have to override any of the methods. A few of the marker interfaces already exist in the JDK like Serializable and Cloneable.

Can we have interface without abstract methods?

Type of methods: Interface can have only abstract methods. An abstract class can have abstract and non-abstract methods.


1 Answers

Why do Java introduces some interface which has no methods defined in it?

This are called Tagged or Marker interface. These are not used for any use or operation. These methods are used to tag or marking a class. So that you can determine whether someclass is a child of those classes.

about the second question

If you look closely you can see the declaration is

 private static native void registerNatives();

So registerNatives is a native methods.

So what is native methods. If you see this so question

The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.

Native methods are usually used to interface with system calls or libraries written in other programming languages.

So these methods are loaded from native codes. So you don't need to declare the body of the methods but still they are not abstract as they have their implementation from native codes.

like image 79
stinepike Avatar answered Sep 18 '22 12:09

stinepike