Java中的接口和继承

先决条件: Java中的接口 , Java与多重继承

null

一个类可以扩展另一个类和/或实现一个或多个接口。 interface_2

// Java program to demonstrate that a class can
// implement multiple interfaces
import java.io.*;
interface intfA
{
void m1();
}
interface intfB
{
void m2();
}
// class implements both interfaces
// and provides implementation to the method.
class sample implements intfA, intfB
{
@Override
public void m1()
{
System.out.println( "Welcome: inside the method m1" );
}
@Override
public void m2()
{
System.out.println( "Welcome: inside the method m2" );
}
}
class GFG
{
public static void main (String[] args)
{
sample ob1 = new sample();
// calling the method implemented
// within the class.
ob1.m1();
ob1.m2();
}
}


输出

Welcome: inside the method m1
Welcome: inside the method m2

接口继承: 一个接口可以扩展其他接口。 interface_inheritance

// Java program to demonstrate inheritance in
// interfaces.
import java.io.*;
interface intfA
{
void geekName();
}
interface intfB extends intfA
{
void geekInstitute();
}
// class implements both interfaces and provides
// implementation to the method.
class sample implements intfB
{
@Override
public void geekName()
{
System.out.println( "Rohit" );
}
@Override
public void geekInstitute()
{
System.out.println( "JIIT" );
}
public static void main (String[] args)
{
sample ob1 = new sample();
// calling the method implemented
// within the class.
ob1.geekName();
ob1.geekInstitute();
}
}


输出:

Rohit
JIIT

一个接口还可以扩展多个接口。

// Java program to demonstrate multiple inheritance
// in interfaces
import java.io.*;
interface intfA
{
void geekName();
}
interface intfB
{
void geekInstitute();
}
interface intfC extends intfA, intfB
{
void geekBranch();
}
// class implements both interfaces and provides
// implementation to the method.
class sample implements intfC
{
public void geekName()
{
System.out.println( "Rohit" );
}
public void geekInstitute()
{
System.out.println( "JIIT" );
}
public void geekBranch()
{
System.out.println( "CSE" );
}
public static void main (String[] args)
{
sample ob1 = new sample();
// calling the method implemented
// within the class.
ob1.geekName();
ob1.geekInstitute();
ob1.geekBranch();
}
}


输出:

Rohit
JIIT
CSE

为什么Java中的类不支持多重继承,但可以通过接口实现? 由于不明确,类不支持多重继承。对于接口,没有歧义,因为方法的实现是由Java 7之前的实现类提供的。在Java8中,接口也有方法的实现。因此,如果一个类实现了两个或多个接口,并且实现的方法签名相同,那么它也必须在类中实现该方法。参考 Java与多重继承 详细信息。

本文由 尼茨海伦德拉 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享