I have multiple classes, and am attempting to call a method in a different class.
This should work, but it gives errors:
TheMethods method = new TheMethods();
Java tells me that the constructor TheMethods() is undefined.
What I am doing wrong?
Edit:
I needed to pass a reference to my main class and initialize it.
In your constructor you have a parameter MCTag m. If you are going to use this constructor you would need to do it like this:
TheMethods method = new TheMethods(MCTag m);
Constructors are like any other method and have to have the correct parameters in order for it to work correctly.
EDIT:
It would look something like this:
MCTag myTag;
TheMethods method = new TheMethods(myTag);
method.selectPlayer();
The only constructor you provide on TheMethods is
public TheMethods(MCTag m) {...
Which takes an MCTag parameter, and you are attempting to call a no-arg constructor which, as the compiler is telling you, does not exist.
Add the default constructor with no args
public TheMethods() {
}
the only ctor i see in your code is:
public TheMethods(MCTag m)
but you don't pass any values in your sample code here
there realy isnt any TheMethods() ctor defined
to reference a public method in another class, call
Class.Method();
Related
I have read in many sources and books that constructor is used to initialise the fields when an object is created. I have also read that JVM provides a default constructor if I don't mention one. What is the purpose of a constructor if it is not required to initialise the fields like the one I have mentioned below?
I also understand that a constructor without parameter is required as
it is necessary during object creation when an argument is not passed
(when programmer-defined constructors with parameters exists).
Is it necessary for JVM to provide a constructor which is actually not required?
public class test {
int a;
public test() {
//this constructor is useless
}
public static void main(String[] args)
{
test ob= new test();
System.out.println(ob.a);
//this prints 0 which means a constructor is not required in intialising `a`
}
}
A constructor like test() makes sense if the programmer defines it since there could be other constructors which takes argument.
But why is it necessary for JVM to provide one when no constructor is declared by the programmer?
I have already tested and proved that initialising a field doesn't require constructor.
Also what does the default constructor look like?
The problem is that while you know the default constructor doesn't do anything in this example, in future the constructor might do something even if you don't realise it is and you might not be able to re-compile everywhere the code is used reliably. So the safest, simplest thing to do is to always call a constructor which might change in the future and let the JIT optimise away the constructor if it doesn't actually do anything.
The byte code always calls a contructor, whether you provide one or not. When you compile code which uses the default constructor it cannot assume the constructor doesn't do anything useful as you can add something to it later to do something useful. e.g.
Say you change
public class Test {
int a;
// public Test() { //this constructor does nothing
}
to
public class Test {
int a;
final List<String> strings = new ArrayList<>();
// public Test() { //this constructor does something now.
}
or
public class ServerTest {
final List<String> strings = new ArrayList<>();
}
public class Test extends SuperTest {
int a;
// the default constructor has to call super();
}
The constructor now initialised the strings field. You can change this class without having to re-compile everywhere it is used and say, hey, my constructor now does something useful, you should call it now.
The reason the JVM adds a default constructor if you haven't provided one is down to inheritance. Say for example you have 3 classes (A, B & C) in which B extends A and C extends B. Now when you instantiate C it will call the constructor of C and also the constructors of B and A. If a constructor was missing in one or more of these classes then the instantiation would fail. So having the compiler automatically add a default constructor avoids error like this. You may not need to actually do any work in your constructor, but it's required for the JVM to instantiate the object.
The constructor(s) (both default and custom one(s)) is not only used to initialize the fields of an object but also to initialize the object itself even if it has no fields at all. Calling the constructor, JVM allocates memory for this object and creates its reference.
It is the compiler, and not JVM, who inserts a default constructor on absence.
A default constructor is needed because the constructor of the base class needs to be called from a constructor.
The default constructor looks like:
public Test() {
super();
}
Here while you are creating the object new test(),
here parenthesis states the default constructor of object test.After creating the object,if you didnot give any constructor the default constructor is constructed by jvm.so after construction of your object first call goes to your default constructor.
The default constructor is a no argument constructor called automatically by the compiler when you haven't defined any constructor. Anyway, a constructor as the one you defined, can be also called a default constructor.
It basically calls the superclass' constructor making use of the super() method.
So the default constructor called automatically would be something like:
public ClassName(){
super();
}
Java's Compiler creates a Default Constructor if no other constructor is defined for the class.
But why?
The compiler's job is to chain the Subclass's constructor to the Super Class(ultimately Object class). It's not the Compiler's work to give a default constructor to your class therefore Java is doing it for you.
To do the chaining, it first checks if there is any constructor in the class, if yes it will add super() to that constructor.
If there is no constructor idefined in the class in order for the compiler to do a proper chaining, Java adds a default constructor and a call to super() into it.
Why ?
Because every class is a subclass of an Object class (directly or indirectly), it will inherit an object class, to do so the said Object class must be fully initialised. This is done by the default constructor.
Following this tutorial:
http://developer.android.com/training/notepad/notepad-ex2.html
In Step 2, this method gets called:
registerForContextMenu(getListView());
which is a public method of Activity. Now, I'm a bit of a Java newbie here - I thought if you wanted to call an instance method of a superclass you needed to preface it with this. E.g.
this.registerForContextMenu(getListView());
Is it just a style thing here? Is there any difference between
this.registerForContextMenu
and simply
registerForContextMenu
No, there is no difference.
You don't have to use this., but it is often done anyway to make the code clearer.
For one thing, it makes it easy to tell if a method is static or not if you use the convention of calling instance methods like this:
this.registerForContextMenu()
and static methods like this:
ClassName.staticRegisterForContextMenu()
you do not have to use this. If you ommit it it is assumed you called method in this scope. One particular example when this may help could be i.e.:
Boolean someVar;
public function setMe( Boolean someVar ) {
this.someVar = someVar;
}
In this case, w/o this you would get the error.
To call a method of superclass either you need object of superclss or keyword super .
eg.
superObject.superclassMethod();
super.superclassMethod();
this is a reference of the current object. this can be used to call method of a class in which it is used. this can never be used to call a superclass method.
As for
this.registerForContextMenu()
and
registerForContextMenu()
no such difference. you can use either of them.
Both ways are correct for calling a method on the current (this) instance of the class. Non private methods are inherited from super classes, so you can use the same syntax to call such methods.
I have a function in my superclass (Speler) that is called kiesKaart:
public Kaart kiesKaart(int spelerIndex){...}
In my subclass function, I have the same function with an other parameter that overrides (i do have #Override before it, changing this to #Override() does not help...) the super function:
public int kiesKaart(Kaart lak){...}
In my main I have an array of Spelers, where only the first is an Speler and the others are AiSpelers (this is the name of the subclass):
spelerArr[0] = new Speler(hand[0]);
for (int i=1;i<AANTALSPELERS;i++) {
spelerArr[i] = new AiSpeler(hand[i]);
}
Later on in my code I address spelerArr[i].kiesKaart, so now I want the code to address the correct instance of kiesKaart.
How can I do this?
The signatures do not match. So you are not overriding the method in super class. The compiler will complain if you use #Override. The signature of the method also includes the type of the parameter.
You overloaded the method by creating a new one with the same name and different arguments. Override is a different thing.
Using #Override will do nothing here because the two methods are different. The first one returns type Kaart given an int, and the second returns type int given a Kaart.
In other words, to make sure you are calling the right method, you need to make sure you send the right parameter (int for the first, Kaart for the second).
I believe you are going to have to use instanceof to determine if it is a Speler or AiSpeler and cast it to the appropriate object before calling kiesKaart.
You are overloading your superclass method, not overriding. Having an annotation does not change this fact.
If you want to determine the type of the calling object (polymorphism) you have to override the method - same parameter list, same return type or a subclass (as of Java 5) and of course the same name.
This might be helpful as a quick reference on what is possible and what not, and how to call it
Does a constructor have to use all parameters that are passed to it?
For example: if there are three parameters passed to construct a new object, must all of the parameters be assigned?
Thanks in advance!
Technically no - you do not have to assign all parameters that are passed.
But the more important question is - why pass them on the first place if they are unused?
UPDATE
Let's assume you have this class:-
public final class SomeClazz {
private final int foo;
public SomeClazz(int foo,int bar){
this.foo = foo;
}
}
And you are invoking it this way:-
SomeClazz clazz = new SomeClazz(2,4);
There is no technical problem with this but as I mentioned above it does not make sense to have a constructor that takes 2 parameters but does not use it. In that case, you should create a constructor that takes just one parameter. Otherwise you are misleading the calling application into thinking that both arguments are being used to create the object.
In general, no. But if you're accepting a parameter and not doing anything with it, why is it there? For example:
class Foo {
public Foo(int w, int h) {
width = w;
height = 10;
}
private int width;
private int height;
}
In the constructor, h is not used. It could be removed from the constructor parameter list.
A constructor, just like any method in Java, does not have to use all its parameters. The call to the constructor, though, needs to supply values for all declared parameters.
A constructor is not required to use all parameters. Not using all parameters raises the interesting question of why they're all not used. This answer assumes you mean that you don't use all of the passed in parameters.
The short answer is no. A constructor, like any method does not have to use everything that is passed to it. However the purpose of a constructor is to "set up" your object, so not using a parameter seems pointless. If you are worried about potentially using a parameter sometimes, overload the constructor.
Of course. In Java, a constructor is a method call, after all; all parameters must have a value.
That will depend of the design of the classes, here is a list of possible repercussions:
1) the constructor will crash and throw and exception
2) the constructor wont crash but when you call a method of the class.
3) the constructor wont crash but you might not be able to assign a value to a property since it is marked as read only.
if you are the owner of the class my advice is too user overloaded constructors.
http://en.wikipedia.org/wiki/Function_overloading
If I do this in Java to call a method name from a class dynamically, it works.
MainApp app = new MainApp();
Method meth = app.getClass().getMethod("myMethod", MyParameterType.class);
//call method
meth.invoke(app, new MyParameterType("hello"));
But this worked because I know the constructor in the invoke method. But if I were to pass the Method object as a parameter to some other classes, and I don't know who is the constructor, I cannot invoke the method any more. Even if I know, I may not want to create a different object to just make a call to the method. For eg:
//This is in the class call MainApp.java.
//There is a method in MainApp.java that looks this way: myMethod(MyParameterType param);
MainApp app = new MainApp();
OtherClass myClass = new OtherClass();
Method meth = app.getClass().getMethod("myMethod", MyParameterType.class);
myClass.callMe(meth);
//Inside OtherClass.java
public void callMe(Method meth) {
//call method
meth.invoke(########, new MyParameterType("hello"));
}
In this case, what should I put for the ######## parameter? Within the context of OtherClass.java, the base constructor object wouldn't be known. And why would I need if since meth is already a Method type that I just call like a function?
Thanks
Assuming it's an instance method, you've got to have an instance to call the method on, just like anything else. How you get hold of that instance will depend on what you're trying to do; you could pass in a Constructor, or a reference to an existing object, or some interface which will create the instance when you ask it to... we can't really give you any advice on which approach is the most suitable without knowing what you're trying to do.
If it's a static method, you can pass null for the first argument.
What it seems you are looking for or thinking about is the concept of `lambda functions``. Those can be called in isolation.
A Method type is not a standalone method, but more like a 'path' into an object. Compare this with a relative URL like /subscribe.html. Out of context this is pretty useless, but when bundled with a site like www.example.com it makes sense.
As such, Method can only be used in combination with an instance. (edit: as John mentioned, unless it's a static method of course which do not need instances)
If you can safely invoke a method without providing an instance, it should be a static method, in which case any instance provided is ignored, you can give it null.
If you have to provide an instance of the object, there is no way around this.
If the developer who write the method has labelled it non-static incorrectly, I suggest you discuss with them why they did it.