【问题标题】:Method with same name and different return type is achieved in c# but not in java [duplicate]在c#中实现了具有相同名称和不同返回类型的方法,但在java中却没有[重复]
【发布时间】: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,请告诉我您的建议。

标签: java c#


【解决方案1】:

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

因此,在 Java 中,您不能在一个类中拥有两个具有相同名称、相同参数(但返回类型不同)的方法。 (当然on方法可以覆盖其他方法并缩小*返回类型,但这是覆盖而不是重载)

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

【讨论】:

    猜你喜欢
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多