它是一个空接口(没有字段或方法)。标记接口的例子有可序列化、可克隆和远程接口。所有这些接口都是空接口。
null
public interface Serializable { // nothing here }
实时应用中使用的标记接口示例:
- 可克隆接口 :java中存在可克隆接口。朗包。中有一个方法clone() 对象 班实现可克隆接口的类表明,clone()方法为该类的实例创建字段对字段的副本是合法的。 在未实现可克隆接口的类实例上调用对象的clone方法会引发异常CloneNotSupportedException。按照惯例,实现此接口的类应该重写对象。clone()方法。 参考 在这里 更多细节。
JAVA
// Java program to illustrate Cloneable interface
import
java.lang.Cloneable;
// By implementing Cloneable interface
// we make sure that instances of class A
// can be cloned.
class
A
implements
Cloneable
{
int
i;
String s;
// A class constructor
public
A(
int
i,String s)
{
this
.i = i;
this
.s = s;
}
// Overriding clone() method
// by simply calling Object class
// clone() method.
@Override
protected
Object clone()
throws
CloneNotSupportedException
{
return
super
.clone();
}
}
public
class
Test
{
public
static
void
main(String[] args)
throws
CloneNotSupportedException
{
A a =
new
A(
20
,
"GeeksForGeeks"
);
// cloning 'a' and holding
// new cloned object reference in b
// down-casting as clone() return type is Object
A b = (A)a.clone();
System.out.println(b.i);
System.out.println(b.s);
}
}
输出:
20 GeeksForGeeks
- 可串行化接口 :java中存在可序列化接口。io包。它用于使对象有资格将其状态保存到文件中。这叫做 系列化 . 未实现此接口的类的任何状态都不会序列化或反序列化。可序列化类的所有子类型本身都是可序列化的。
JAVA
// Java program to illustrate Serializable interface
import
java.io.*;
// By implementing Serializable interface
// we make sure that state of instances of class A
// can be saved in a file.
class
A
implements
Serializable
{
int
i;
String s;
// A class constructor
public
A(
int
i,String s)
{
this
.i = i;
this
.s = s;
}
}
public
class
Test
{
public
static
void
main(String[] args)
throws
IOException, ClassNotFoundException
{
A a =
new
A(
20
,
"GeeksForGeeks"
);
// Serializing 'a'
FileOutputStream fos =
new
FileOutputStream(
"xyz.txt"
);
ObjectOutputStream oos =
new
ObjectOutputStream(fos);
oos.writeObject(a);
// De-serializing 'a'
FileInputStream fis =
new
FileInputStream(
"xyz.txt"
);
ObjectInputStream ois =
new
ObjectInputStream(fis);
A b = (A)ois.readObject();
//down-casting object
System.out.println(b.i+
" "
+b.s);
// closing streams
oos.close();
ois.close();
}
}
输出:
20 GeeksForGeeks
- 远程接口 :java中存在远程接口。rmi包。远程对象是存储在一台机器上并从另一台机器访问的对象。所以,要使一个对象成为远程对象,我们需要用远程接口标记它。在这里,远程接口用于标识其方法可以从非本地虚拟机调用的接口。任何远程对象都必须直接或间接实现此接口。RMI( 远程方法调用 )提供了一些方便的类,远程对象实现可以扩展这些类,以方便远程对象的创建。
本文由 高拉夫·米格拉尼 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END