简体   繁体   中英

How can i return a value from an overridden method in the superclass AND the method in the subclass?

I realized I had this issue when i was typing down simple code to find the perimeter and rectangle to demonstrate method overriding in java. can i return the area (length * breadth) in the same subclass method?

package override;

class perimeter{
int length,breadth;

perimeter(){length = breadth = 0;}//default constructor

perimeter(int length, int breadth){
this.length = length;
this.breadth = breadth;
}

int show(int length, int breadth){
    return 2*(length + breadth);
}
}

class area extends perimeter{
area(int length, int breadth){
    super(length,breadth);

}


int show(int length, int breadth){
    return super.show(length, breadth);
    // how can i return this too? :  return length * breadth;
}

}

public class overrideshapes {
public static void main(String args[]){
    area shape1 = new area(5,10);
    System.out.println(""+ shape1.show(shape1.length,shape1.breadth));


}

}

I don't know what are you trying to do, but I'm going to explain a few more what I'm thinking about your question.

I think you want to calculate perimeter and areas for different polygons, so the best way is to create an Interface, something like this.

public Interface Calculate {
    public int calculateArea(int length, int width);
}

Then you should to implement your interface, in many clase according your polygons, for example:

public class Square implements Calculate {

    @Override
    public int calculateArea(int length, int width){
        return length*width; //Because this is the way you calculate square areas
    }
}

So you have to implement for your polygons your interface method "calculateArea" using @Override annotation, so each polygon knows how to calculate its area.

Hope it helps to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM