java - If i call Insert method from C i want to get output "Now in Class B", But actually i get "Now in Class C" why? how can it be solved? -
public interface d{ public abstract string joo(); public abstract string foo(); public bean tem(){ joo(); } } public abstract class a{ protected abstract string joo(); protected abstract string foo(); protected bean tem(){ joo(); } } public class b extends impliments d{ protected string joo(){ system.out.println("now in class b"); } protected string foo(){ super.tem(); } } public class c extends b{ protected string joo(){ system.out.println("now in class c"); } protected string foo(){ super.tem(); } public void insert(){ super.foo(); } }
if call insert method c want output "now in class b", "now in class c" why? how can solved? when calling foo method in class c ,i want output "now in class c".
you can't - @ least not without refactor.
here's code cleaned clearer. note @override
indicates method overrides inherited method.
public abstract class { protected abstract string joo(); protected abstract string foo(); protected string tem() { return joo(); } } public class b extends { @override protected string joo() { system.out.println("now in class b"); return "from b"; } @override protected string foo() { return super.tem(); } } public class c extends b { @override protected string joo() { system.out.println("now in class c"); return "from c"; } @override protected string foo() { return super.tem(); } public void insert() { super.foo(); } } public void test() { c c = new c(); // valid - prints in class c c.insert(); // valid - prints in class c c.foo(); }
see how insert
on c
calls b.foo
calls a.tem
calls joo
. a.joo
implemented in b
overriden in c
final result c.joo
.
Comments
Post a Comment