java - Method overriding and inheritance -
public class circle { public static final double pi = 3.141592654; protected double radius; public circle(double radius) { this.radius = radius; } @override public string tostring() { return "class = " + getclass().getsimplename() + " (radius = " + radius + ")"; } } public class planecircle extends circle { private double centerx, centery; public planecircle(double radius, double centerx, double centery) { super(radius); this.centerx = centerx; this.centery = centery; } @override public string tostring() { return super.tostring(); } }
suppose above 2 classes in different files.
when create instance of planecircle
(in java file) following 2 lines...
planecircle planecircle1 = new planecircle(3, 6, 7); system.out.println(planecircle1.tostring());
what in console output is
class = planecircle (radius = 3.0)
the tostring()
method in planecircle
calls super.tostring()
, , tostring()
method in circle
should give "circle" when use getclass().getsimplename()
.
my question is, why output "planecircle" instead of "circle" in case though have created instance of subclass (planecircle)? have reflection?
planecircle1
instance of planecircle
, means getclass()
return planecircle.class
(i.e. class
instance represents planecircle
class) , getclass().getsimplename()
return class's name - "planecircle".
it doesn't matter getclass().getsimplename()
called method of base class circle
, since when call method without instance variable, calling on current instance (i.e. getclass()
same this.getclass()
, , this
instance of planecircle
in code sample).
Comments
Post a Comment