class { dog() } class b extends { cat() } public static void main(string args[]) { obj1 = new a(); b obj2 = new b(); obj3 = new b(); } when class a object created obj1 call dog(),whenclass b's object created obj2 call cat() , dog().but a obj3= new b() created method should called?please answer thanks
to give quick , dirty answer, think mean:
both methods can called. (in example, neither method called because, excluding other errors, aren't calling of methods)
i won't polymorphism try best:
if have:
class { public void dosomething() { system.out.println("bark!"); } } and
class b extends a{ public void dosomething() { system.out.println("meow!"); } } and
public static void main(string[] args) { obj1 = new a(); b obj2 = new b(); obj3 = new b(); // , want see happens when do: obj1.dosomething(); // prints bark! obj2.dosomething(); // prints meow! obj3.dosomething(); // prints meow! } notice important thing here both classes have exact same name method, though different things!
that (i think) key concept polymorphism trying understand: can redefine method in subclass! however, redefine method, method has have same name! then, compiler pick version of method defined @ lowest level.
in example
class { public void dog() { system.out.print("dog!"); } } class b extends { public void cat() { system.out.println("cat!"); } } public static void main(string args[]) { obj1 = new a(); b obj2 = new b(); obj3 = new b(); obj1.dog() // method class has, defined. print dog! } however, b defines own method, called cat(). can b.cat().
but don't forget: b extends a, has, b has.
so can call b.dog()!
obj3 since linked new b() can call both dog() , cat().
if named same thing, obj3 call version of method defined in class b. however, in case, 2 seperate methods, 1 not overriding other.
to answer question.
if return code, calling a obj3 = new b();
obj3.dosomething(); // prints meow! this because defined obj3 new b() takes on method dosomething() in way class b defines it.
Comments
Post a Comment