Java strange syntax - (Anonymous sub-class) - java

I have come across below strange syntax, I have never seen such snippet, it is not necessity but curious to understand it
new Object() {
void hi(String in) {
System.out.println(in);
}
}.hi("strange");
Above code gives output as strange
thanks

You've created an anonymous sub-class of Object, which introduces a method, called hi, after which you invoke this method with parameter "strange".
Let's suppose you had:
class NamedClass extends Object {
void hi(String in) { System.out.println(in); }
}
NamedClass instance = new NamedClass();
instance.hi("strange");
If this class was needed at exactly one place, there's no real need of being named and so on - by making it an anonymous class, you get rid of its name, the class gets defined and instantiated and the hi method invoked immediately within a single expression.

You've created an annonymous sub-class of Object and then invoke the method.
Four types of anonymous inner class exists :-
1)Inner class,
2)Static nested classes
3)Method local inner classes
4)Anonymous inner classes
In Annonymous inner classes,you can define,instantiate and use that inner object then and there

This is perfectly normal and is Called an anonymous class it is used very often where if u want to pass an object reference to a function you will do it with anonymous classes or for the use of callbacks, now .hi at the end is valid because you just used the new operator to instantiate an object of type Object and you have a reference to it so that's why it works.

Related

Java: Iterate through Nested Classes

Currently, I have a number of nested classes inside an outer class. Each nested class has an overriden toString method. My goal is to iterate through these nested classes to access the value returned by the overriden toString without initializing every single nested class. I've tried iterating through the array returned by Class#getDeclaredClasses
The simplified outer class:
class MyClass {
static class NestedClassOne {
#Override
public String toString() {return "One";}
}
static class NestedClassTwo {
#Override
public String toString() {return "Two";}
}
}
The method I've tried, using the Class#getDeclaredClasses array:
for (Class<?> NestedClass : MyClass.class.getDeclaredClasses()) {
System.out.println(NestedClass.toString());
}
This method, to my dismay, only prints the following:
class ... MyClass$NestedClassTwo
class ... MyClass$NestedClassOne
Your toString() is invoked directly on the class object. I.e., it calls Class<T>.toString() not NestedClassOne.toString(). For that you need to use reflection:
Class<NestedClassOne> clazz = NestedClassOne.class;
Method method = clazz.getMethod( "toString" );
NestedClassOne obj = clazz.newInstance();
Object result = method.invoke( obj );
System.out.println( result );
I'll repeat my comments however:
This sounds like a bad idea. You really shouldn't be using reflection like this. An enum or something similar would likely be a better fit.
It's just kind of obviously super brittle. It throws numerous exceptions, which enums won't. If the code structure changes at all (changing to a different constructor for example) it breaks. If the method name changes, the compiler can't detect it. Etc. I wouldn't want to maintain code that works the way you are asking for.
My goal is to 1) iterate through these nested classes to 2) access the value returned by the overridden toString without initializing every single nested class.
The first part you are doing. The second part is not possible.
The toString() methods you are trying to call are instance methods.
You can't call an instance method until you have created an instance.
You can't create an instance of a class without triggering1 the static initialization of the class.
What your attempted code is actually doing is calling the toString() method on the Class objects. That gives you the names of the classes.
#markspace's answer shows how to create an instance and call the toString() method via reflection. The caveats are that it assumes that each class has a no-args constructor, and that creating the instances doesn't have undesirable side-effects.
1 - There are scenarios involving classes with cyclic dependencies where an instance of a class may be created before its static initialization has completed.
I agree with #markspace's comments. I'm not sure what the real purpose of this is, but there is likely to be a better (more robust) way than calling toString() methods. (For example ... using a custom annotation with runtime retention.)
Even if there isn't, the constraint of not initializing the classes seems artificial to me: is this a premature optimization?

Can you use the class for calling method? [duplicate]

This question already has answers here:
Difference between Static methods and Instance methods
(10 answers)
Closed 4 years ago.
Whenever I have to call a method from another class, I first create an object and then call it through the object. But while I was writing some code, I mistakenly wrote classname.methodname(); and it worked.
I would usually write,
classname obj = new classname();
obj.methodname();
Here is the actual code:
Class 1
public class Dataset {
public static List<ECCardData> getDataset() {
//Code
}
in Class 2
List<ECCardData> dataset = Dataset.getDataset();
I noticed that the methodname() was static. Was that the reason?
Yes, for static methods (with suitable access modifier) you can call directly with your class by
YourClass.yourMethod();
and this way, too
YourClass anObject = new YourClass();
anObject.yourMethod();
Happy coding.
I hate answering my question, but I found the correct answer.
When a method is declare static, only one instance of that method will exist. When you create an object a new instance of the method is created, which is not possible for a static method. Therefore you use the class name.
classname.methodname(); //only one instance
classname obj;
obj.methodname(); //instance with obj as Object(IDE gives warning, should not be allowed, ideally)
The basic paradigm in Java is that you write classes, and that those
classes are instantiated. Instantiated objects (an instance of a
class) have attributes associated with them (member variables) that
affect their behavior; when the instance has its method executed it
will refer to these variables.
However, all objects of a particular type might have behavior that is
not dependent at all on member variables; these methods are best made
static. By being static, no instance of the class is required to run
the method.
You can do this to execute a static method:
classname.staticMethod();//Simply refers to the class's static code But
> to execute a non-static method, you must do this:
>
> classname obj = new classname();//Create an instance
> obj.nonstaticMethod();//Refer to the instance's class's code

Why we are allowed to create an object of a class inside the same class?

I am just trying to figure out why it is possible to do such thing but it is not possible in some other programming languages like C++.
Here is an example of what I am asking:
public class A{
private A objectOfTheSameClass;
public A()
{
objectOfTheSameClass=new A();
}
}
Because it's not explicitly prohibited.
JLS section 8.8.7 that defines that body of a constructor does not mandate a compile-time error for such a case. The only case when a compile-time error should happen is when a constructor invokes itself with this:
It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this.
More precisely:
Except for the possibility of explicit constructor invocations, and the prohibition on explicitly returning a value (§14.17), the body of a constructor is like the body of a method (§8.4.7).
Since a method is allowed to invoke itself (recursion), a constructor is also allowed to do the same.
This will not compile because it calls this:
public class A{
private A objectOfTheSameClass;
public A() {
objectOfTheSameClass= this();
}
}
Your code, although it compiles, will throw a StackOverflowError because the constructor of A creates itself a new instance of A. The compiler can't detect every infinite loop in your code...
It can be useful sometimes, for example in the "singleton" pattern is used to have exactly one instance of a class by creating an object of the same class as a class field, making it accessible via a public method and making the constructor private.
The instances are not created until the runtime, so the class is fully defined. It's up to you to use this in a proper way.

Working with the class keyword in Java

I don't really understand how the class keywords work in some instances.
For example, the get(ClientResponse.class) method takes the ClientResponse.class. How does it use this when it gets it, and what are the advantages over just passing an instance of it?
SomeClass.class
returns a Java Class object. Class is genericized, so the actual type of SomeClass.class will be Class<SomeType> .
There are lots of uses for this object, and you can read the Javadoc for it here: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html
In ClientResponse.class, class is not a keyword, neither a static field in the class ClientResponse.
The keyword is the one that we use to define a class in Java. e.g.
public class MyClass { } /* class used here is one of the keywords in Java */
The class in ClientResponse.class is a short-cut to the instance of Class<T> that represents the class ClientResponse.
There is another way to get to that instance for which you need an instance of ClientResponse. e.g
ClientResponse obj = new ClientResponse();
Class clazz = obj.getClass();
what are the advantage over just passing a instance of it?
In the above example you can see what would happen in case obj was null (an NPE). Then there would be no way for the method to get the reference to the Class instance for ClientResponse.
The Class class, which is different from the class keyword, is meta-data describing instances. It tells you about the methods, data members, constructors, and other features of the instances that you create by calling new.
For example get(ClientResponse.class) method takes the
ClientResponse.class how does it uses this when it gets it and what
are the advantage over just passing a instance of it?
You can't pass an instance of ClientResponse to this method; it's expecting meta-data about all instances of ClientResponse. If you passed an instance, you'd expect that the method might change the state of that instance. But passing the meta-data about all instances might allow the method to create a new kind of instance (e.g. a dynamic proxy) or do something else that depends on the meta-data about all instances of ClientResponse. See the difference?
A class is a "blueprint" of the object. The instance is a object.
If we have
public class SomeClass {
int a;
SomeClass(int a) {
this.a = a
}
}
We can have an instance of this class
SomeClass c = new SomeClass(10);
c is an instance of the class. It has a integer a with value 10.
The object SomeClass.class represents a Class.
Here SomeClass.class is a object of the type Class which has the information that SomeClass is
a concrete class with
one constructor
with a integer member variable
and lots more other metadata about the class SomeClass. Note that it does not have a value for a.
You should use get(c) incase you are planning to do something with a instance of c like call c.a or other useful functions to manupulate/get data of the instance.
You should use get(SomeClass.class) when the get returns something based on the fact that the argument is some type of class. For example, if this is a method on a Registry class which has a map which retrieves a implementation class based on type of class passed in.
The very most important fact is - you don't need to have an instance to call the method. It's critically useful in situations when you cannot for some reason instantiate a class, e.g. it's abstract, or have only private constructor, or can only be correctly instantiated by some framework, like Spring or JSF.
You can then call get to obtain an object of a requested type without even knowing where it does come from and how it get's created.
Here ClientResponse.class is an instance of Class<ClientResponse>. In general Class object represents type of an object. When you create new instance:
Object obj = new ClientResponse()
you can retrieve the class (type) of that object by calling:
obj.getClass()
So, why would you pass Class objects around? It's less common, but one reason is to allow some method create arbitrary number of instances of a given class:
ClientResponse resp = ClientResponse.newInstance();
There's a lot of ways Class objects can be used. This is used for Reflection. Below is a link that can help you understand more.
http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
Whenever we compile any Java file, the compiler will embed a public, static, final field named class, of the type java.lang.Class, in the emitted byte code. Since this field is public and static, we can access it using dotted notation along with class name as in your case it is ClientResponse.class.

Java: How To Call Non Static Method From Main Method?

I'm learning java and now i've the following problem: I have the main method declared as
public static void main(String[] args) {
..... }
Inside my main method, because it is static I can call ONLY other static method!!! Why ?
For example: I have another class
public class ReportHandler {
private Connection conn;
private PreparedStatement prep;
public void executeBatchInsert() { ....
} }
So in my main class I declare a private ReportHandler rh = new ReportHandler();
But I can't call any method if they aren't static.
Where does this go wrong?
EDIT: sorry, my question is: how to 'design' the app to allow me to call other class from my 'starting point' (the static void main).
You simply need to create an instance of ReportHandler:
ReportHandler rh = new ReportHandler(/* constructor args here */);
rh.executeBatchInsert(); // Having fixed name to follow conventions
The important point of instance methods is that they're meant to be specific to a particular instance of the class... so you'll need to create an instance first. That way the instance will have access to the right connection and prepared statement in your case. Just calling ReportHandler.executeBatchInsert, there isn't enough context.
It's really important that you understand that:
Instance methods (and fields etc) relate to a particular instance
Static methods and fields relate to the type itself, not a particular instance
Once you understand that fundamental difference, it makes sense that you can't call an instance method without creating an instance... For example, it makes sense to ask, "What is the height of that person?" (for a specific person) but it doesn't make sense to ask, "What is the height of Person?" (without specifying a person).
Assuming you're leaning Java from a book or tutorial, you should read up on more examples of static and non-static methods etc - it's a vital distinction to understand, and you'll have all kinds of problems until you've understood it.
Please find answer:
public class Customer {
public static void main(String[] args) {
Customer customer=new Customer();
customer.business();
}
public void business(){
System.out.println("Hi Harry");
}
}
Java is a kind of object-oriented programming, not a procedure programming. So every thing in your code should be manipulating an object.
public static void main is only the entry of your program. It does not involve any object behind.
So what is coding with an object? It is simple, you need to create a particular object/instance, call their methods to change their states, or do other specific function within that object.
e.g. just like
private ReportHandler rh = new ReportHandler();
rh.<function declare in your Report Handler class>
So when you declare a static method, it doesn't associate with your object/instance of your object. And it is also violate with your O-O programming.
static method is usually be called when that function is not related to any object behind.
You can't call a non-static method from a static method, because the definition of "non-static" means something that is associated with an instance of the class. You don't have an instance of the class in a static context.
A static method means that you don't need to invoke the method on an instance. A non-static (instance) method requires that you invoke it on an instance. So think about it: if I have a method changeThisItemToTheColorBlue() and I try to run it from the main method, what instance would it change? It doesn't know. You can run an instance method on an instance, like someItem.changeThisItemToTheColorBlue().
More information at http://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods.
You can think of a static member function as one that exists without the need for an object to exist. For example, the Integer.parseInt() method from the Integer class is static. When you need to use it, you don't need to create a new Integer object, you simply call it. The same thing for main(). If you need to call a non-static member from it, simply put your main code in a class and then from main create a new object of your newly created class.
You cannot call a non-static method from the main without instance creation, whereas you can simply call a static method.
The main logic behind this is that, whenever you execute a .class file all the static data gets stored in the RAM and however, JVM(java virtual machine) would be creating context of the mentioned class which contains all the static data of the class.
Therefore, it is easy to access the static data from the class without instance creation.The object contains the non-static data
Context is created only once, whereas object can be created any number of times.
context contains methods, variables etc. Whereas, object contains only data.
thus, the an object can access both static and non-static data from the context of the class
Since you want to call a non-static method from main, you just need to create an object of that class consisting non-static method and then you will be able to call the method using objectname.methodname();
But if you write the method as static then you won't need to create object and you will be able to call the method using methodname(); from main. And this will be more efficient as it will take less memory than the object created without static method.
Useful link to understand static keyword
https://www.codeguru.com/java/tij/tij0037.shtml#Heading79

Categories