edits...
Does instantiating a class with an overloaded constructor from main() also call the parameterless constructor?
Do applications that instantiate a plugin class with an overloaded constructor with plugin.execute() necessarily call the parameterless constructor?
to clarify: I'm expecting one answer for main() and one for plugin.execute() entry points.
class pluginObj {
public pluginObj() {} // default /primary constructor
public pluginObj(int altConst) {} // alternate constructor
public execute() { //... plugin entry code goes here
}
public main() { //... test entry code goes here
}
}
context: class is a plugin for another application, using main() for testing in the short term I know that Junit is the correct way to do this in the long run.
Constructors works like this
Public class ExampleClass{
private int in1;
private int in2;
public ExampleClass(){
this(5) // overloading using some default value
} // overloads the below and if called super is called here and not below, this then runs the functionality of the below constructor
public ExampleClass(int in1){
super(); // hidden call to parent constructor
this.in1 = in1;
} // doesn't overload the below or above, and if called simpley sets int1
public ExampleClass(int in1, int in2){
super(); // hidden call to parent constructor
this.in1 = in1;
this.in2 = in2;
} // everything is done here, has nothing to do with the other 2 constructors
}
meaning depeiding on how you do the overload ... it always calls the super(), as well as whatever else was defined in the other constructor, also note that 1 instance always get intantiated using only 1 constructor, but as shows may still use the other constructors to provide multiple starting points for classes, it can for instance be used to make classes easier to create, or force some permanent values relevant to the class when it is intantiated.
It's also possible to alter what "super()" call is used see JavaDoc
Simply call the super with the arguments of the constructor you wish to use
Related
public class Store {
// instance fields
String productType;
// constructor method
public Store(String product) {
productType = product;
}
// advertise method
public void advertise() {
String message = "Selling " + productType + "!";
System.out.println(message);
}
// main method
public static void main(String[] args) {
String cookie = "Cookies";
Store cookieShop = new Store(cookie);
cookieShop.advertise();
}
}
In this class, the constructor for the class is called in its own main method. Why wouldn't this recursively call itself infinitely?
EDIT: From the future, yes; this quite a noob question that could be, and has been solved by reading the docs.
Constructors of a class are used to construct class-instances. Static methods are methods of the class, not of its instances (although they can be accessed through its instances). A class is loaded through a ClassLoader. Most classes are loaded and constructed through the ClassLoader.getSystemClassLoader(), the JVM takes care of constructing the class.
The class Store is already loaded when main(...) is executed and the call to the constructor creates, as explained above, an instance of that class, not the class itself. Thus, no recursive calls occur.
As was pointed out by #AndyTurner, even if an instance method were to call a constructor, this would not necessarily lead to a recursion. The constructor constructs a new instance, the old instance is decouple from the new instance.
Main method is a static method and it is called one time when application is starting. Once application started, main method can't run again.
When you making a store object, It is true that constructor is running. But it does not calling main method again.
I'm trying to call the static method getPod in the class DropPod from another class with DropPod.getPod() except I need a parameter for DropPod.getPod().
How do I change the getPod method so I can access it from the other class?
I know I could just make land() static, but I don't want to do that. I'd like to try to learn to do it this way.
public class DropPod {
protected static boolean opened;
int pos = Random.NormalIntRange(1777, 1794);
public static void getPod(DropPod drop)
{
drop.land();
}
public void land() {
Level.set(pos, Terrain.DROPPOD_CLOSED);
Game.updateMap(pos);
opened = false;
Dungeon.observe();
}
}
Option 1: You can create a new instance of DropPod in your other class. With this instance, you can just call Object.getPod().
Option 2: You already mentioned this, but you could make land a static method as well and DropPod.getPod() should work.
Static methods of a class cannot reference non-static methods of its objects.
If you only want 1 instance of DropPod, you can add it as a property of it's own class. Something like a Singleton Pattern.
Add a non-static overload for getPod() with no parameters, that just calls land().
Maybe remove the static version completely. Hard to see why this method exists at all actually, or why it is called getPod() when it doesn't return anything. I would remove it and just call land() directly.
Also hard to see why you want to call a method that calls land() when you don't have anything to land. You need to rethink all this.
I have main class with a private static method. I want to access this method from another java class. I tried some ways,however they didnt work. How can I access the method?
below main class like this;
public class RandomGenerate {
public static void main(String[] args) throws Exception {
System.out.print.ln("main method");
}
private static synchronized void createRandom(PersonObj person, int number, List s) {
System.out.println("deneme");
}
}
And I want to call createRandom from another java class like this;
public class Deneme {
RandomGenerate rg = new RandomGenerate();
RandomGenerate.createRandom(person, number, sList);
}
Then, netbeans shows method has private access.
You shouldn't access a private function/variable from outside of that class. If you need to access a private variable of a class, you can create an accompanying getter for that variable, and call the getter function on the class.
For functions, if the class you are trying to access the function from is in the same package, or is a subclass as the class with the function, change private to protected. protected allows members in the same package, or subclasses, to access the item, but nothing outside of the package.
A good read on visibility in Java is: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
That shows a table:
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Primarily
If you need to use it outside the class, make it public (or protected if you need it only in subclasses, or the default [no keyword at all] if you need it just in the package). If you need to use it outside the class and it's private and you can't make it not private, that's a design problem you should fix.
But...
...you can work around it using reflection (tutorial, docs), which allows you to get the method and call it even though it's private. Once you have the Method object, you have to call setAccessible to true before you call it.
But again, that's a workaround. Use the correct access modifier.
private methods are not accessible from another class by definition. If you need to call it you can create another public method that internally calls the private one or change the access modifier to public/protected/default.Example:
private static String secretMethod() { return "secret"; }
public static String knownMethod() { return secretMethod(); }
You will want to choose the proper access modifier for the method, the options are: public, protected, default (which is indicated by not providing a modifier), and private.
A good explanation is here: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
As mentioned in the comments, you can use public to open it up, but if you don't want such a wide access, you could start with default (which allows you to access the method if you're in the same package), or protected (which is the same as default, but also allows child classes to access the method, if you wanted to extend the class).
As a general rule, stick with the most restrictive permission. It's easier to open up permissions later, but very hard to remove them.
You can not access Private methods outside the class which defines this method. You should make it Public to give full access to any classes or protected to give access to all the classes in the same package.
Click [here] http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html For more reference.
If you really wish to access private method, you will have to use Java Reflection. See this sample code.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Workspace {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ClassWithPrivateMethod cwpm = new ClassWithPrivateMethod();
Method m = cwpm.getClass().getDeclaredMethod("privateMethod", String.class);
m.setAccessible(true); //This is a key statement for accessing private methods
m.invoke(cwpm, "test");
}
}
class ClassWithPrivateMethod {
private void privateMethod(String someParam){
System.out.println("I am private!!!");
System.out.println("Parameter: " + someParam);
}
}
This code will print following output:
I am private!!!
Parameter: test
Just change the visibility from private to public so other Instances can access them. Private means it is only for the own class available.
If I have the method public void send() { /* some code */ } in a class and have a child of this class also have a method public void send() { /* some code*/ }, how do I ensure that the child must call super.send() somewhere in the send() method that it's trying to override?
I was wondering about this because I've written in APIs where if you don't call the super of that method when overriding it, it'll throw an exception telling me that I haven't called the super method. Is this hard coded or can this be done with some keywords in Java?
You can't really, but you can...
class MySuperClass {
public final void send() {
preSend();
// do the work...
postSend();
}
protected void preSend() {
// to be overridden in by sub classes
}
protected void postSend() {
// to be overridden in by sub classes
}
}
You can do this by adding an abstract method (don't see another way) :
abstract class MyClass
{
public final void send() // forbid changing this.
{
// do something
doSend():
}
protected abstract doSend(); // no external calls
}
http://en.wikipedia.org/wiki/Call_super
What you're trying to do is an anti-pattern; you can do it (many Java core classes do), but you shouldn't - unless you have a really good reason for it.
Except for this bit, all answers provided here are correct.
Conceptually, this is like 'delegating to a child'. To achieve this, the parent class should implement final method which invoke an abstract method, which the child is supposed to implement.
abstract class Parent {
public final void invoke() {
// pre invoke code
doInvoke():
// post invoke code
}
protected abstract doInvoke(); // child should implement this
}
You can't really force a subclass to call the base one. One thing you can do is to change your send method into a base (final) "send" and a "sendcore" (virtual) which would be overriden by the subclasses. The base "send" would set some flag stating that "sendcore" hasn't been called, and then call "sendcore". When it returns it can check whether the child "sendcore" has called the base class.
There is no keyword that enforces this. In my opinion, you either
Provide the subclass with all the information (via protected methods or what not) it needs to completely override and change the send call itself, or...
Document the API so that it is known that they must eventually call send themselves via super. I would imagine most people who are overriding a superclass method would do this if enough of the class is abstracted anyway.
There's nothing built into Java to enforce calling a superclass method. One approach to this is to use private flags in the superclass together with a delegation method. Something like this:
public class Super {
private boolean inSend;
private boolean superCalled;
public final void send() {
inSend = true;
superCalled = false;
doSend();
inSend = false;
if (!superCalled) {
throw new IllegalStateException("Failed to call super.doSend()");
}
}
protected void doSend() {
if (!inSend) {
throw new IllegalStateException("Cannot call doSend() directly");
}
superCalled = true;
// base class functionality
}
}
I'm wondering if there is a way to specify that a method gets called in advance of a class method. I know something like this should be posssible, since JUnit has before(), what I want to do is similar.
Here is a concrete example of what I'd like to do
class A {
public void init(int a) {
System.out.println(a);
}
#magic(arg=1)
public void foo() {
//
}
public static void main() {
A a = new A();
a.foo();
}
}
//Output: 1
Basically I want an annotation to tell either the compiler or the jvm call init() before foo()
If you have interface A you can wrap instances of this interface with Proxy and inside invoke method of its InvocationHandler you are free to check whether method is annotated and perform some actions depending on that:
class Initalizer implements InvocationHandler {
private A delegate;
Initializer(A delegate) {
this.delegate = delegate;
}
public Object invoke(Object proxy, Method method, Object[] args) {
if (method.isAnnotationPresent(magic.class)) {
magic annotation = method.getAnnotation(magic.class);
delegate.init(magic.arg);
}
method.invoke(delegate, args);
}
}
A realA = ...;
A obj = Proxy.newProxyInstance(A.class.getClassLoader(), new Class[] {A.class}, new Initializer(realA));
Or you can try using "before" advice of AspectJ. It will be something like the next:
#Aspect
public class Initializer {
#Before("#annotation(your.package.magic) && target(obj) && #annotation(annotation)")
private void initialize(A obj, magic annotation) {
a.init(annotation.arg);
}
}
I'm not sure that snippets are working, they just illustrate idea.
Why are you doing this? Are you attempting to avoid having a constructor with many arguments (using setters then calling init) or are you avoiding having many constructors that all have similar arguments? If this is the case, you can use a builder pattern.
public class Foo {
int a, b, c, d, e;
Foo(int a, int b, int c, int d, int e) { this.a=a; /*etc*/ }
}
public class FooBuilder {
int a,b,c,d,e;
FooBuilder A(int a) { this.a=a; return this;}
FooBuilder B(int b) { this.b=b; return this;}
//etc
Foo create(){ return new Foo(a,b,c,d,e);
}
If this doesn't work, I'd suggest looking into AOP. I'd mark the methods that must have init() called already with an annotation [perhaps #requires('init') or the like] and make you AOP framework insert the proper code. Be careful that multiple init's either don't have side effects or that you do proper synchronization on your has_init_been_called state.
Just call Init() at the start of foo()?
AOP does this with what are known as pointcuts
AspectJ might have what you need.
Simplistically speaking, you would add before advice to your foo() method which would call init()
There is no direct way to do this in the java language. What you are seeing in JUnit is the framework making a decision about how to run the methods by calling the methods annotated with #Before first. It is very easy to find annotated methods and run them, but that is the responsibility of the caller.
The problem you present is too simple to know the right way to a solution. AspectJ does address this need by manipulating the byte code (essentially calling the init() method when foo() is called by changing the bytecode to make that happen), but I can't imagine introducing that as a hack around a problem.
If you can present an interface or a wrapper object to this class, you could do it that way. But I would suggest you post the ugly hack that got you into this situation in the first place in a separate question, and then post how your current hack solution requires that method calls be intercepted and why that is the case, and if there are better workarounds. That way we can help address the underlying need better.
Have a look at AspectJ. It will help you do what you are asking.
I assume that the problem here is as follows:
You have a constructor that can partially build the object, but can't completely build it because of the way the class must be constructed. (I can't think of an example offhand.)
So you need an init() method that will finish construction.
So you want to have some kind of guarantee that init() will be called right after the constructor.
My suggestion is to use a factory object or method. The simplest way is to make the constructor private, add a construct() method with the parameters of the constructor or something of that sort, and then have the construct() method both create the object and call init(), then return it.