gpt4 book ai didi

java - 如果我们可以简单地覆盖父类(super class)的方法或使用抽象类,为什么还要使用接口(interface)呢?

转载 作者:搜寻专家 更新时间:2023-11-01 01:07:51 25 4
gpt4 key购买 nike

<分区>

我有两个程序,一个使用接口(interface)实现,另一个仅使用类实现 -我读过使用接口(interface)的优点是它可以提供它自己的父类(super class)方法的实现,但这可以使用抽象类或方法覆盖来完成。接口(interface)的作用是什么?
在什么样的层次结构和情况下使用界面最有利?

界面

interface Shape
{
void area(int x, int y);
}
class Rectangle implements Shape
{
@Override
public void area(int length, int breadth)
{
System.out.println(length*breadth);
}
}
class Triangle implements Shape
{
@Override
public void area(int base, int height)
{
System.out.println(base*height);
}
}
public class ShapeUsingInterface
{
public static void main(String X[])
{
Rectangle r = new Rectangle();
Triangle t = new Triangle();

r.area(5, 4);
t.area(6, 3);
}
}



class Shape
{
void Area(int x, int y)
{
System.out.println(x*y);
}
}
class Rectangle extends Shape
{

}
class Triangle extends Shape
{
@Override
void Area(int base, int height)
{
System.out.println((0.5)*base*height);
}
}
public class CalculateArea
{
public static void main(String X[])
{
Rectangle r = new Rectangle();
Triangle t = new Triangle();

r.Area(4, 5);
t.Area(6, 8);
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com