How to call grandparent constructor with parameters in Java? -
this question has answer here:
maybe question have many people ask, still don't know how answer.
i have a, b, c class.
c extends b, b extends a.
the main method in c class.
if want call constructor method parameters in c class,
how can do?
thanks much.
a class
public class { public a() { system.out.println("a construtor"); } public a(int a, int b) { system.out.println("a.a:"+ + "/b.b:"+b); } }
b class
public class b extends a{ public b() { system.out.println("b construtor"); } public b(int a, int b) { system.out.println("b.a:" + + "/b.b:" + b); } }
c class
public class c extends b{ public static void main(string[] str) { c c = new c(); } public c() { // super(1,2); // how call constructor parameters system.out.println("c constructor"); } }
class c not explicitly extend class a, via class b c extends a, hence able access constructors of a, via constructors of class b.
by using super(1,2) in class c's constructor call class b's constructor has 2 int parameters. need change class b's arg constructor following:
public class b extends a{ public b() { system.out.println("b construtor"); } public b(int a, int b) { super(a,b); system.out.println("b.a:" + + "/b.b:" + b); }
}
bear in mind following:
1)when no constructor supplied class, java creates default non-arg constructor.
2)if class extends class b, class b requires constructor , superclasses must called @ first.
Comments
Post a Comment