why have a constructor called in the same class? - java

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.

Related

Overloaded constructors from main() and plugin.execute()

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

new className().methodName(); VS className ref = new className();

I came across a code which my colleague uses inside an eventListner, which is :
private void someActionPerformed(java.awt.event.ActionEvent evt) {
new className().methodName(); //public class and public void methodName()
}
I was pretty sure that :
private void someActionPerformed(java.awt.event.ActionEvent evt) {
className ref = new className(); //public class and public void
ref.methodName();
}
is the better option than his, as the previous method instantiates a class every time it is called.
Am I wrong? Any suggestion is appreciated, Please correct me if I am wrong
.
Both do the same thing, however one of them (the first) is 1 line shorter.
Your approach is usually recommended when you need to go through more than 2-3 objects, so new Foo().getBar1().getBar2().doStuff() is usually not recommended since it can degrade into spaghetti code and hinder the understandability of the code.
The first code-sample instantiates a new Object of Type className.methodName.
For this to work, methodName has to be a static nested class of Type className.
Attention: This could as well be a typo. Did you mean new className().methodName()?
The second sample creates a new instance of className and calls its method methodName.
Some example code:
public class Test {
public static void main(String[] args) {
new Test.test(); // instantiates the inner class
Test t = new Test(); // instantiates Test
t.test(); // calls method #test of Test-instance
}
public String test() {
return "Test";
}
public static class test {
}
}
In order to judge what's the best solution your example does not give enought information. Is the method some static utility code or is an instance of className useful? It depends...
Whenever an object is instantiated but is not assigned a reference variable, it is called anonymous object instantiation.
With anonymous object you can call it's instance method also:
new className().methodName();
In your case this is the anonymous object which doesn't have reference variable.
In the statements:
className ref = new className();
ref.methodName();
ref is the reference variable to hold the className object, so you can call instance methods of className on ref variable.
The benefit of using anonymous notation is, if you want to do only limited (may be calling single method and so on..) operation with the underlying object the it is a good approach. But if you needs to perform more operation with the underlying object then you need to keep that object in a reference variable so that you can use that reference to perform multiple operations with that object.
Regarding the performance there are not much difference as both are in methods scope, as soon as method completes both the objects are valid candidates for the garbage collection.
Both the methods instantiates a class in the code. If you want to reuse the class object every time the method is called, you can declare it as a member of the class where the method resides. For eg:
class AnotherClass{
private ClassName ref;
AnotherClass(){
ref = new ClassName()
}
private void someActionPerformed(java.awt.event.ActionEvent evt) {
ref.methodName();
}
}
This way, everytime your method someActionPerformed is called on an object of AnotherClass, it will reuse the ref object instead of instantiating it everytime.
About the edit,
public class ClassName {
static class InnerClass{
// A static inner class
}
public void methodName() {
// A method
}
}
class AnotherClass{
private void someActionPerformed(java.awt.event.ActionEvent evt){
// This creates an instance of the inner class `InnerClass`
new ClassName.InnerClass();
// However I believe, you wanted to do:
new ClassName().methodName();
}
}
new className.methodName(); --> if you are using this convention in your code then calling another method name will result to different object's method name and you lose your values.
className ref = new className();
ref.methodName(); -> here you are creating a reference and make assiging a newly created object and you are calling the method's on it. Suppose if you want to call another method on the same object it will helps.
The first approach they will mostly use for listenere which is anonymous class.
Both options create a new Class every time they are called. The advantage of the second over the first option would be if you wanted to reuse that class later in the method.
IMHO this is a little bit more understandable code for the answer provided by DaniEll
public class Test {
public static void main(String[] args) {
new Test.test(); // instantiates the inner class
Test t = new Test(); // instantiates Test
t.test(); // calls method #test of Test-instance
}
public void test() {
System.out.println("Outer class");
}
public static class test {
public test() {
System.out.println("Inner class");
}
}
}

Java calling methods non/static and private/public

I just had some method calling scenarios I was unsure of, and was hoping someone could help clear some up for me.
a) If I was in the SalesMethod class and I wanted to call the sales method from the region method how would I do that? (private method calling public method)
b) What about sales calling purchase? (public calling public from within same class)
c)If I was in SalesMethod, what would be a way to call the futureSales method? Would I have to create an instance for it since it's non static?
Thanks in advance.
public class SalesMethod
{
public static double sales ()
{
code
}
private static void region ()
{
code
}
public static double purchase ()
{
code
}
public void futureSales ()
{
code
}
}
a) private method calling public method is ok since public mean "visible from everywhere".
public static double region()
{
sales();
}
b) public method calling public method is ok for the same reason.
b') public method calling private method is ok if the private method is in the same class than the public one.
c) to call a non-static method, you have to create an instance since you call it "on" an object. You can't call it from a static method the way you do in the example above.
static means "relative to a class"
non-static is relative to an object, you can see that as an action performed by the object.
If I was in the SalesMethod class and I wanted to call the sales method from the region method how would I do that? (private method calling public method)
They are both static, so you can call them everytime you need to.
sales();
// Or
SalesMethod.sales();
What about sales calling purchase? (public calling public from within same class)
They are both static, so you can call them everytime you need to.
purchase();
// Or
SalesMethod.purchase();
If I was in SalesMethod, what would be a way to call the futureSales method? Would I have to create an instance for it since it's non static?
Yes.
SalesMethod instance = new SalesMethod();
instance.futureSales();

Recursive object access to private methods

Why does the following code print "YO"? Whose printYo() is being called? I would think that this code would not compile because printYo() is private to t.
public class Test {
private void printYo() {
System.out.println("YO");
}
public void doubleTrouble(Test t) {
t.printYo();
}
public static void main(String[] args) {
Test test = new Test();
test.doubleTrouble(new Test());
}
}
What can I do to make sure the outer object doesn't mutate the argument class?
printYo() is private to t
No. That method is private in regards to the class Test. Any piece of code within Test can use it.
What can I do to make sure the outer object doesn't mutate the argument class?
Java does not have any built in mechanism to refuse access to members on a per instance basis. (If that is what you meant.)
You are calling the method with in the class , which sound correct for the output . Even if you call the main method from different class it gives the same output.

Need help to get two classes to assist each other

i'm currently just fooling around with different classes to test how they work together, but im getting an error message in NetBeans that i cant solve. Here's my code:
class first_class.java
public class first_class {
private second_class state;
int test_tal=2;
public void test (int n) {
if (n>2) {
System.out.println("HELLO");
}
else {
System.out.println("GOODBYE");
}
}
public static void main(String[] args) {
state.john();
TestingFunStuff.test(2);
}
}
class second_class
public class second_class {
first_class state;
public int john () {
if (state.test_tal==2) {
return 4;
}
else {
return 5;
}
}
}
Apparently i can't run the method "john" in my main class, because "non static variable state cannot be referenced from a static context" and the method "test" because "non static method test(int) cannot be referenced from a static context".
What does this mean exactly?
Screenshot of the error shown in netbeans: http://imageshack.us/photo/my-images/26/funstufffirstclassnetbe.png/
It means state must be declared as a static member if you're going to use it from a static method, or you need an instance of first_class from which you can access a non-static member. In the latter case, you'll need to provide a getter method (or make it public, but ew).
Also, you don't instantiate an instance of second_class, so after it compiles, you'll get a NullPointerException: static or not, there needs to be an instance to access an instance method.
I might recommend following Java naming conventions, use camelCase instead of under_scores, and start class names with upper-case letters.
The trick here to get rid of the error message is to move the heavy work outside of main. Let's assume that both lines are part of a setup routine.
state.john();
TestingFunStuff.test(2);
We could create a function called setup which contains the two lines.
public void setup() {
state.john();
TestingFunStuff.test(2);
}
Now the main routine can call setup instead, and the error is gone.
public static void main(String[] args) {
setup();
}
However, the other members are correct in that your instantiation needs some cleanup as well. If you are new to objects and getting them to work together might I recommend the Head First Java book. Good first read (note first not reference) and not all that expensive.
Classes can have two types of members by initialization: static and dynamic (default). This controls the time the member is allocated.
Static is allocated at class declaration time, so is always available, cannot be inherited/overridden, etc. Dynamic is allocated at class instantiation time, so you have to new your class if you want to access such members...
It is like BSS vs heap (malloc'd) memory in C, if that helps..

Categories

Resources