【发布时间】:2017-02-28 23:47:03
【问题描述】:
我是 JAVA 环境的新手,在尝试实现具有相同名称和不同返回类型的方法时遇到问题。在 C# 中,我使用方法隐藏概念来实现这一点。有没有更好的方法在 JAVA 中实现相同的功能。请查找代码 sn-p 以供参考。请在这方面给我建议
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;
}
}
【问题讨论】:
-
您还没有添加代码片段
-
我已附上代码sn-p,请告诉我您的建议。