问题
abstract class Cell<Q> {
public abstract Q getValue(); // abstract method
}
class Cell1 extends Cell<Integer> {
public Integer getValue() {// abstract method implementation
return 0;
}
}
class Cell2 extends Cell<String> {
public String getValue() { // abstract method implementation
return "razeel";
}
}
class test
{
public static void main(String[] a)
{
Cell obj=new Cell1();
int ab=(Integer) obj.getValue();
Cell objs=new Cell2();
String str=objs.getValue().toString();
System.out.println("ab=================== "+ab);
System.out.println("String=================== "+str);
}
}
- Can we call this an example of method overloading in java. If not why?
- Is it possible to have methods with same signature but different return types in java?
回答1:
This is clearly not method overloading . Overloading means your method having different parameters return type has nothing to do with overloading.
public void method(int a,int b);
public void method(String s,int b);
Or you can say different number of arguments.
public void method(int a,int b,int c);
public void method(int a,int b);
what you are doing is overriding.
回答2:
Above shown code sample is an example of method overriding. this is the way by which java implements runtime polymorphism. In java if an overriden method is called using superclass refernce, java determines which version of that method to execute depending upon the type of object being referred to at the time of call, not depending on the type of variable. consider
class Figure{
double dim1;
double dim2;
Figure(double dim1,double dim2){
this.dim1=dim1;
this.dim2=dim2;
}
double area(){
return 0;
}
}
class Rectangle extends Figure{
Rectangle(double dim1,double dim2){
super(dim1,dim2);
}
double area(){
double a;
a=dim1*dim2;
System.out.println("dimensions of rectangle are "+dim1+" "+dim2);
return a;
}
}
class Triangle extends Figure{
Triangle(double dim1,double dim2){
super(dim1,dim2);
}
double area(){
double a=(dim1*dim2)/2;
System.out.println("base & altitude of triangle are "+dim1+" "+dim2);
return a;
}
}
class test{
public static void main(String[] args){
Figure r;
Rectangle b=new Rectangle(10,10);
Triangle c=new Triangle(10,10);
r=b;
System.out.println("area of rectangle fig "+r.area());
r=c;
System.out.println("area of triangle fig "+r.area());
}
}
output: dimensions of rectangle are 10.0 10.0 area of rectangle fig 100.0 base & altitude of triangle are 10.0 10.0 area of triangle fig 50.0
for 2nd qstn: no. signature means unique. return type is not a part of signature
回答3:
Can we call this an example of method overloading in java.
No.
If not why?
Overloading means "same name, different parameters", but you've got subclasses implementing methods, nothing more.
Is it possible to have methods with same signature but different return types in java?
No.
来源:https://stackoverflow.com/questions/11554290/confusion-in-method-overloading-using-abstract-class-in-java