2016-10-19 4 views
-4

JAVA環境では新しいですが、同じ名前と異なる戻り値の型を持つメソッドを実装しようとしています。 C#では、これを実現するためのメソッド隠蔽の概念を使用しています。 JAVAでこれを実装するためのよりよい方法はありますか?参考のためにコードスニペットを見つけてください。同じ名前で異なる戻り値の型を持つメソッドは、C#では実現できますが、Javaでは実現しません。

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: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; 
} 
} 
+0

コードスニペットを追加していません –

+0

コードスニペットを添付しました。 。 – Karthikk

答えて

0

そこ方法記述子によって識別されます。メソッドの記述は、クラスやメソッド名で構成さだけでなく、この

C#はで私に助言してくださいメソッドのパラメータの型ですが、戻り値の型はメソッド記述子の一部ではありません。

Javaでは、1つのクラスで同じ名前(同じ戻り値の型)を持つ2つのメソッドを持つことはできません。 (もちろん、メソッドは他のメソッドをオーバーライドして戻り値の型を絞り込むことができますが、オーバーロードではなくオーバーライドします)

(* Doubleを返すメソッドでNumberを返すメソッドをオーバーライドできます)それらを変更することはできませんし、何かを返すメソッドでvoidを返すメソッドをオーバーライドすることはできません)

関連する問題