具有相同名称和不同返回类型的方法在c#中实现,但在java中无法实现

本文关键字:实现 java 但在 返回类型 方法 | 更新日期: 2023-09-27 18:13:49

我是JAVA环境的新手,在尝试实现具有相同名称和不同返回类型的方法时面临问题。在c#中,我使用了方法隐藏的概念来实现这一点。有没有更好的方法在JAVA中实现相同的功能?请找到供参考的代码片段。请在这方面给我建议

c#:

class Shape
{
public int Width { get; set; }
public int Height { get; set; }
public void Print()
{
Console.WriteLine("Base class is called");
}
}

class Table: Shape
{
public int m_tableHeight;
public int m_tableWidth;
public string m_modle;
public Table(int tableWidth, int tableHeight,string modle)
{
m_tableHeight = tableHeight;
m_tableWidth = tableWidth;
m_modle = modle;
}
public new string Print()
{
return m_modle;
}
}
JAVA:

public class Shape
{
public int getWidth()throws Exception{
return getWidth();
}
public void setWidth(int value)throws Exception{
setWidth(value);
}
public int getHeight()throws Exception{
return getHeight();
}
public void setHeight(int value)throws Exception{
setHeight(value);
}
public void Print()throws Exception{
System.out.println("Base class is called");
}
}
public class Table
 extends Shape
{
public  int m_tableHeight;
public  int m_tableWidth;
public  String m_modle;
public Table(int tableWidth,int tableHeight,String modle)throws Exception{
m_tableHeight=tableHeight;
m_tableWidth=tableWidth;
m_modle=modle;
}
//Throws error as return type is incompatible with shape.print()
public String Print()throws Exception{
return m_modle;
}
}

具有相同名称和不同返回类型的方法在c#中实现,但在java中无法实现

在Java中,方法由方法描述符标识:方法描述符由类和方法名以及方法参数的类型组成,但是返回类型不是方法描述符的一部分!

所以在Java中,你不能在一个类中有两个具有相同名称,相同参数(但返回类型不同)的方法。(当然,一个方法可以覆盖另一个方法并缩小返回类型,但这是覆盖而不是重载)

(*你只能缩小它们(用返回Double的方法覆盖返回Number的方法),但你不能改变它们,你不能用返回其他值的方法覆盖返回void的方法)