Java中的接口和继承

作者: Arvin Chen 分类: Java 来源: Break易站(www.breakyizhan.com)

Java中的接口和继承

一个类可以扩展另一个类,并且/可以实现一个或多个接口。
Java中的接口和继承

// 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

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

Java中的接口和继承

// 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中的接口和继承 - Break易站
    转载请保留页面地址:https://www.breakyizhan.com/java/4235.html
    扫描二维码添加微信 
  • ,领取淘宝优惠券,淘宝购物更优惠。现在添加微信,还可以领取机械键盘优惠券!添加微信后,分享淘宝选中的机械键盘给淘宝机器人即可领取!
    支持我们,就用微信淘宝!

    发表笔记

    电子邮件地址不会被公开。 必填项已用*标注

    更多阅读