The following code is a testing program. Why i can't use A(int a), in this program?
public class A {
int a;
void meth(int b) {
a+=b;
}
A(int a) {
this.a=a;
}
}
class B extends A {
int a;
void meh2(int b) {
a+=b;
}
}
why can't pass parameter to constructor? What the reasons? Netbeans error message:
constructor A in class tma1.A cannot be applied to given types; required: int found: no arguments reason: actual and formal argument lists differ in length
In the class B, you need constructor. If you mean that you can't call A from B, that's just because you're extending class A, so you need to use super, which refer to the superclass. For example B could be:
class B extends A {
B(int a) {
//You can put additional code here
// This calls the constructor of A
super(a);
//You can put additional code here
}
int a;
void meh2(int b) {
a+=b;
}
}
Otherwise you need to assign something to the variable a in class B, if you're not omitting something in code
Unless a class has a defined constructor, it automatically has a no-arg constructor that merely calls super()
.
The complaint from your compiler seems to be: "your no-arg constructor [that you can't see] is calling up to a parent no-arg constructor that doesn't exist."
Class A
doesn't have a no-arg constructor because there's another one defined (so java doesn't have to create one).
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.