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

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");
}
}
}

Related

How to create a Variable with scope global and but should not be a STATIC

Need a variable to hold a value which will be assigned once and will be used by every method of a class
if I specify it as non static variable it is not holding the value
Class Test{
private String test;
public void method1(){
test = "String1";
}
public void method2(){
System.out.println(test.length());
}
}
Getting Null Pointer exception. the value of the test will be used in every method.
Could anyone help me, how to fix the issue.
The NullPointerException will be thrown whenever the test variable is null and you try to invoke methods on that variable. In your case, when you invoke method2() before method1(). That has nothing to do with global, local or whatever, as Long Vu already mentioned.
So first you should make sure, you don't access an uninitialized variable. Then, if you need a class with a single instance, which should be accessible application wide, you can implement this using the singleton pattern. For more about it, have a look at this Wikipedia page: https://en.wikipedia.org/wiki/Singleton_pattern
Maybe your problem is that you are creating multiple objects of class Test.
For example this should work:
Test test1=new Test();
test1.method1(); //call this first then other methods
test1.method2();
You should use this object "test1" as a parameter wherever you need it.
If you want to access the variable globally then create a Singletone class:
class Test{
private static Test single_instance = null;
private String test;
// private constructor restricted to this class itself
private Test(){
}
// static method to create instance of Singleton class
public static Test getInstance(){
if (single_instance == null)
single_instance = new Test();
return single_instance;
}
public void setTest(String value){
test = value;
}
public String getTest(){
return test;
}
public static void main(String args[]){
Test test = Test.getInstance();
test.setTest("String1");
test.getTest();
}
}

How is it possible to create object in Class definition itself?

I have some doubt on how this works, consider a simple Java program:
package com.example;
public class Test {
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
public void print() {
System.out.println("This is demo");
}
}
This is pretty straightforward program.
However, I have doubt at (1). We are creating an instance of Test, but this is still in the definition of Class Test. How is this possible?
Any explanation to help this would be great.
The instance will be created at run-time.
By then, compile-time is over and all of the code of your application (including all class definition) will be "ready".
Even if you call a constructor of a class that has not been encountered by the JVM up to that point, it will dynamically load the class (in its entirety) before executing the constructor call. Note that a) this might actually fail at run-time, in which case you get a ClassNotFoundError, and b) that cannot happen in your case, because you are calling the constructor of the class from itself (so it must have been loaded already).
The compiler does not run any of your code (not even things like static initializers) during compilation.
But it does make sure (during compilation) that every method or constructor that you are trying to call does in fact exist. Again, this could theoretically fail at runtime (if you mess up class files), in which case you would get a NoSuchMethodError.
First We have to Compile this Porgram using javac After Compilation It will give a Class File.
Now time to Execute Your Class Using java which Invokes JVM and load the Class File to the Class Loader.
java fileName.Class
And here
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
All we know static Content (either it is Variable or Method In Java) Of class loaded when ClassLoader loads a Class
As You see Main Method is a static Method. and So, It will Automatically Load into the ClassLoader with class File.
Now JVM First find the public static void main(String... args) in class. Which is a static Content means Its a part of Class but not a part of Class Instance. There is no need of Class Instance to Invoke this MainMethod`.
main(String... args) will be Invoked without getting Instance of the Class. In that Main Method , Your Class is Getting Instantiated
Test t = new Test(); \\here t is reference Variable to Test Class Object.
Now Because Class is loaded into the class Loader new Test(); will create a New Object in Heap memory Area of JVM and your method
public void print() {
System.out.println("This is demo");
}
will be invoked using t.print() Which is a Instance Method (Not Static), So It needs Class Instance to Invoke print() Method.
Q: Test t = new Test(); (1) <---- How is this possible
A: Because of the "static" in public static void main(String[] args)
The "static" means that method "main()" is independent of any specific class object.
You can create any class object you want - including a new "Test" object.
One of the benefits of defining "main" to be static is that you can use "main()" as a test method for the class. Each class can have it's own "main", and you can test each class individually by specifying that class in your Java command line.
For example:
public class MyClass {
public int add2(int n) {
return n + 2;
}
public static void main (String[] args) {
MyClass unitTest = new MyClass ();
System.out.println ("add2(2)=" + unitTest.add2(2));
System.out.println("Expected result=4");
}
}
Then test as follows:
javac MyClass.java
java MyClass
add2(2)=4
Expected result=4
This question has actually been asked and answered many times. For example:
Why is the Java main method static?
==================================================================
Here are a few more examples that illustrate the point:
public class CreateMyself {
private int value = 0;
private static CreateMyself m_singleton = null;
// EXAMPLE 1: You can legally create an instance in the constructor ...
public CreateMyself () {
value++;
// CreateMyself o = new CreateMyself (); // BAD!!! This will cause infinite recursion and crash your stack!!!
System.out.println ("Leaving constructor, value=" + value + "...");
}
// EXAMPLE 2: You can legally create another instance in a normal class member
public void createAnother() {
// But ... WHY??? Is there anything you can't do directly, in your own instance?
CreateMyself newInstance = new CreateMyself ();
System.out.println ("Leaving createAnother, value=" + value + "...");
}
// EXAMPLE 3: This is a common idiom for creating a "singleton"
// NOTE: for this to work, you'd also make the constructor PRIVATE (or protected), so the client *must* call "getInstance()", instead of "new".
public static CreateMyself getInstance () {
if (m_singleton == null) {
m_singleton = new CreateMyself ();
}
System.out.println ("returning singleton instance...");
return m_singleton;
}
// EXAMPLE 4: Creating an instance in "static main()" is a common idiom
public static void main (String[] args) {
CreateMyself newInstance = new CreateMyself ();
newInstance.createAnother ();
}
}
There are many other possible uses. For example, maybe you'll have a static method that does a database lookup and returns a list matching objects.
Note that most of the cases where it's really useful for a class to have a method where it creates an instance of itself are probably static methods.

Static reference and using Objects which have been initialized outside of a main?

I have a question concerning the use of objects...
I have a class called Area which contains a few methods. I want to access these methods in another class in which an Area object is created.
public class calcAreaObj {
Area areaObj = new Area();
public static void main(String[] args){
areaObj.area(2,3,4);
}
}
Why is it when the class is created as above I get an error("Cannot make a static reference to non-static field areaObj. But when the source code is written such that the Area object is initiaized inside the main statement as below there are no errors...
public class calcAreaObj {
public static void main(String[] args){
Area areaObj = new Area();
areaObj.area(2,3,4);
}
}
Is this because in the first case the Area object is initialized outside of a static statement? If so, why does this matter?
This is because when defined at class scope, areaObj is specific to each instance of calcAreaObj. That's not really what you want, since main is a static method (and so doesn't have an instance of calcAreaObj associated with it). You can either use the second code sample you posted, or you can modify the first one as follows:
public class calcAreaObj {
static Area areaObj = new Area();
public static void main(String[] args){
areaObj.area(2,3,4);
}
}
Additionally, if areaObj doesn't have any state, in this case, you could always declare Area.area as static.
In the first example areaObj is a non-static member of calcAreaObj. This means it can only be accessed using an instance of calcAreaObj.
new calcAreaObj().areaObj.whatever(); //this will work
calcAreaObj.areaObj; //areaObj isn't a static member, won't work
In short: the non-static member doesn't even exist as long as you haven't created an instance of calcAreaObj. In the second example, it's in scope of the method and thus accessible.
For the first situation your creating a local variable for the class which has no relation with the object used in the main. Therefore you have to initialize the object again in the main.
There is a rule: that any block has it's own variables. So if you initialize a variable in block and try to use it outside the block that will give you an error.
For example:
public static void main(String [] arg){
{ Area a = new Area(); }
double number = a.area
}
this doesn't work ...
I wish it is clear

What will happen when we create an object outside the method?

I have a question related to OOP.
what is the effect, if we make an object outside the method.
Is that object becomes global?
Here is some code..
class A(){
String b;
public void c(){
//some code in here}
}
class C(){
A a = new A(); //is this ok and if it is ok what is this mean??
public void p(){
a.c(); //Is this possible??
}
}
It seems like you are very new to Java or Object Oriented Programming.
There are two steps to create an object in Java: Declaration and initialization
Declaration means you are declaring that something exists.
Eg: String title; means, there exists a string object named title.
Initialization is assigning value to it. ie: title = "Hello World!";. But before initializing an object you need to make sure it is declared. Also you can combine declaration and initialization in one statement: String title = "Hello World!";
The scope of the object depends up on where you declare that object.
If you declare it inside a class like this:
class Car {
String name; //These are called fields
static String author = "Farseen"
public void doSomething() {..../*can access name and author*/}
public static void doSomething() {..../*can access author only*/}
}
everything inside the class will have access to it, except the static (we'll get to that in a while) methods.These are called fields
If you decalare it inside a method, only that method will have access to it:
class Car {
public void doSomething() {
String name = "BMW"; //These are called local variables
}
public void doSomeOtherThing() {
//Cannot acccess name
}
}
These are called local variables
If you declare it outside a class, sorry Java does not allow you to do that. Everything must be inside a class.
You can prefix declarations outside methods, that are fields with access modifiers:
public : Makes the field accessible to anyone. It is legal to :
Car myCar = new Car();System.out.println(myCar.name);
private : Makes the field accessible to the methods(functions) inside the class only. It is illegal to :
Car myCar = new Car();System.out.println(myCar.name);
protected : Makes the field accessible to the subclasses of that class. It is also not accessible to users, like private.
Now comes in the static modifier:
It says that the field or method(function) belongs to the entire species of car, instead of individual cars.
It is legal to access the static field author like this: Car.author no need to create an individual car, although it is legal : new Car().author
The static things only know about static things, not individual things.
There is no concept of Global Variables in Java. Although, you can achieve it using some thing like this:
class Globals {
public static String GLOBAL_VARIABLE_MESSAGE = "Hello World!";
}
And use it somewhere in your code using Globals.GLOBAL_VARIABLE_MESSAGE
Hope it helps!
Edit: referring to the code added to the question
class A{ //Parenthesis are NOT needed
// or allowed in class definition:
// 'class A()' is wrong
String b;
public void c(){
//some code in here
}
}
class C{ //Same here. No parenthesis needed
A a = new A(); //Q: Is this ok and if it is ok what is this mean??
//A: Yes, completely ok.
// This means you added
// a field 'a' of type A to the class C
public void p(){
a.c(); //Q: Is this possible??
//A: Of course
}
}
I made some edits to your code and added answers to your doubts
class A{
String b;
public void c(){
//some code in here}
}
class C{
A a = new A(); //is this ok and if it is ok what is this mean??--It is Ok.it means that a is instance variable of type A.
public void p(){
a.c(); //Is this possible?? -- It is possible. since c() is a method in class A.
}
}
Where you create an object has little to do with it being "global". It is all about the scope of accessibily of a reference to that object. To give two extreme opposites, both involving instantiation outside of a method:
public static final File f = new File(new File("/x/a"), "b");
The above line will cause two instances of File to be created: one will become global, the other will be completely inaccessible and disposed of on the spot.

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.

Categories

Resources