Is it important to save all class code as individual .java files like following way?
Outer.java,
Inner.java,
Test.java
Or can I make a single java file as Test.java. Please explain anonymous class, how can we create anonymous class in java, and what is the advantage/disadvantage over normal class?
class Outer {
private int data = 50;
class Inner {
void msg() {
System.out.println("Data is: " + data);
}
}
}
class Test {
public static void main(String args[]) {
Outer obj = new Outer();
Outer.Inner in = obj.new Inner();
in.msg();
}
}
See the Code Conventions for the Java programming language:
Each Java source file contains a single public class or interface.
When private classes and interfaces are associated with a public
class, you can put them in the same source file as the public class.
The public class should be the first class or interface in the file.
I think this should answer your question. As I stated in my comment, it's not recommended to write a file that contains several unrelated classes. However, if you have an associated classes with that one public class you have in the file, you can place them in the same source file.
An anonymous class in Java is a class not given a name and is both declared and instantiated in a single statement. You should consider using an anonymous class whenever you need to create a class that will be instantiated only once.
Although an anonymous class can be complex, the syntax of anonymous class declarations makes them most suitable for small classes that have just a few simple methods.
An anonymous class must always implement an interface or extend an abstract class. However, you don’t use the extends or implements keyword to create an anonymous class. Instead, you use the following syntax to declare and instantiate an anonymous class:
new interface-or-class-name() { class-body }
Within the class body, you must provide an implementation for each abstract method defined by the interface or abstract class. Here’s an example that implements an interface named runnable, which defines a single method named run:
runnable r = new runnable()
{
public void run()
{
//code for the run method goes here
}
};
Here are a few other important facts concerning anonymous classes:
An anonymous class cannot have a constructor. Thus, you cannot pass parameters to an anonymous class when you instantiate it.
An anonymous class can access any variables visible to the block within which the anonymous class is declared, including local variables.
An anonymous class can also access methods of the class that contains it.
yes you can do this , but it should be in small programming,
while in big application you have to make class individual, Java strongly recommended that to make class different file, but it depends on you to do so.
Related
This question already has answers here:
Can we instantiate an abstract class?
(16 answers)
Closed 9 years ago.
When I create the object of an Abstract class, I have to do like this just like an interface.
AbstractClass abstractClass = new AbstractClass() {
#Override
public void abstractMethod() {
}
};
Does this mean that the object of AbstractClass is an anonymous inner class object?
AbstractClass abstractClass = new AbstractClass() {
#Override
public void abstractMethod() {
}
};
This block of code means that you are creating an anonymous class which extends AbstractClass. You can also use the same notation for an interface also.
SomeInterface someImplementingClass = new SomeInterface(){/*some code here*/};
This means you are creating a class that implements SomeInterface.
Note that there are certain limitation when you are creating an anonymous class. As and anonymous class is already extending the parent type, you cannot make it extend another class as in java you can extend only on class.
This code will help understand concept of overriding methods in anonymous classes
class Anonymous {
public void someMethod(){
System.out.println("This is from Anonymous");
}
}
class TestAnonymous{
// this is the reference of superclass
Anonymous a = new Anonymous(){ // anonymous class definition starts here
public void someMethod(){
System.out.println("This is in the subclass of Anonymous");
}
public void anotherMethod(){
System.out.println("This is in the another method from subclass that is not in suprerclass");
}
}; // and class ends here
public static void main(String [] args){
TestAnonymous ta = new TestAnonymous();
ta.a.someMethod();
// ta.a.anotherMethod(); commented because this does not compile
// for the obvious reason that we are using the superclass reference and it
// cannot access the method in the subclass that is not in superclass
}
}
This outputs
This is in the subclass of Anonymous
Remember that anotherMethod is implemented in implemented in the subclass that is created as anonymous class. and a is the reference variable of type Anonymous i.e. superclass of the anonymous class. So the statement ta.a.anotherMethod(); gives compiler error as anotherMethod() is not available in Anonymous.
An object is not a class object (in this context). It is derived from a class. In Java there is a difference between classes and objects, as compared to e.g. prototype based languages (e.g. JavaScript) where this difference does not exist.
In your example you create an anonymous class, create an object of that anonymous class and assign it to a variable; all in one step.
Anonymous classes are always inner classes: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.3
One fundamental properties of attract classes is the fact that there could be no direct instance of this type. Only classes that implement the complete interface of an class can be instantiated.
In order to create an object you need a non abstract class first, by extending the abstract class.
Abstract classes does not have any instances (objects of it's type). I recommend Mavia to take a look at following link for clearness:
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You cannot create an object of an abstract class. They are non-instantiable. What you are doing when you do this is creating a sort of dynamic subclass object, and instantiating that (at the same time). More or less, yes, you can create it the same way as an interface. See this answer for more information.
In fact here you create both: an anonymous inner class, that extends AbstractClass as well as an instance of this anonyomous class, the object. You do not and cannot create an instance of AbstractClass.
Also you declare a variable named abstractClass that has the Type AbstractClass. Inside this variable you store a newly created instance of your newly defined subclass of AbstractClass.
EDIT: You can of course not reuse the anonymous inner class, since it is anonymous, and the only place where an instance of it can be created or rather is created is right here.
Here might be a loop or function in which case you would be able to create many instances of this anonymous inner class. But it would still be only this piece of code where instances are created.
I am wondering what does it mean to have a nested abstract class ? for example,
abstract class A{
abstract class B{
}
}
Are there any use cases or scenario that we might need such as design ? or is there something useful in such pattern ? and why Java allows us to do it ?
In design, you want the base class class A to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which gives you polymorphic behavior), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword. In other hand you want to use only part of functionality of class A so you create class B (as child) to reduce the coupling or implementation dependencies between systems and prevent duplicates.
But bear in mind when you define an inner class, code without inner classes is more maintainable and readable. When you access private data members of the outer class, the JDK compiler creates package-access member functions in the outer class for the inner class to access the private members. This leaves a security hole. In general we should avoid using inner classes. Use inner class only when an inner class is only relevant in the context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc which are used in the context of an outer class. About abstract class, it should be abstract to helpers, suppose your helpers should be too complicated to write abstract form for them.
In your case, I don't remember extensive usage of nested abstract classes, maybe in Swing world.
abstract classes are used to provide a partial implementation of a class for inheritance. it allows you to define the scheme of a class without providing the full definiton, so that it can be specified in a child class. it works somewhat like a Interface in that you can perform any operation specified in the abstract class upon an instance of any classes derived from it. Nested abstracted classes are designed to be inherited by other inner classes (even anonymous ones I think) but not by classes defined outside the outermost class.
public class HelloEveryone{
abstract class Hello{
void SayHello(){
System.out.println("Hello!");
}
abstract void SayHelloAlt();
}
public class HelloWorld extends Hello{
public void SayHelloAlt(){
System.out.println("HelloWorld!");
}
}
public class HelloUniverse extends Hello{
public void SayHelloAlt(){
System.out.println("HelloUniverse!");
}
}
void Go(){
ArrayList<Hello> hellos = new ArrayList<Hello>();
hellos.add(new HelloWorld());
hellos.add(new HelloUniverse());
for (Hello h : hellos){
h.SayHello();
h.SayHelloAlt();
}
}
}
static void main(){
HelloEveryone hello = new HelloEveryone();
hello.Go();
}
Though i have often come across,i dont understand this way of writing code:
Runnable r=new Runnable() {//<----- (braces start here?)
public void run() {
System.out.println("Hello");
}
}; // ?
What is this?
Please explain very clearly.
That's an anonymous inner class. It's creating an implementation of the Runnable interface using code within the braces. As well as implementing interfaces, you can extend other classes. The nice aspects are that you can do this without explicitly creating a separate class, and you can also refer to final local variables (including parameters) within the body of the anonymous inner class.
See the Java tutorial for more details, or just search for "anonymous inner class" for loads of related pages.
As mentioned by others, what is being created here is an anonymous inner class. Specifically, the person who wrote the code is saying:
Instead of an instance of the Runnable class, I want to create a subclass that overrides the "run()" method and create an instance of that. Its not worth my time to create a named subclass, since I'm only going to create this one instance. Instead, just override the method and return the subclass instance I need.
That's an anonymous class declaration - basically, a class that implements the Runnable interface, declared and instantiated inline as an anonymous nested class.
Note that you can also declare anonymous subclasses the same way:
Object o = new Object(){
public String toString(){ return "boo!" };
}
Also note that you can use variables of the enclosing method inside the anonymous class code, but only if the variables are final (because the anonymous class actually gets a copy of the variable).
I would start with these http://www.google.co.uk/search?q=anonymous+classes+tutorial 23 million results.
Basically, it allows you to define an implementation or a subclass without having to create a fully formed class defintiions.
EDIT: For your own interest, see if you can figure out what this does.
Map<String, String> map = new LinkedHashMap<String, String>() {{ // two brackets
put("a", "aye");
put("b", "bee");
put("c", "see");
put("d", "dee");
put("e", "ee");
put("f", "eff");
}};
It's so called 'anonymous class'.
You can do this:
class MyRunnable implements Runnable{
public void run() {
System.out.println("Hello");
}
}
Then:
Runnable r = new MyRunnable();
And achieve the same thing. However, the MyRunnable class that you created is never needed in any other part of your code. So creating a named class is not necessary. The code that you wrote on the other hand is creating an anonymous inner class such that the implementation of the class is precisely where it is needed. It will not be accessible rom anywhere else in the code but that is the idea, you do not need it anywhere else.
I saw this Java snippet in the book Spring in Action, but I'm not familiar with the language construct.
new RowMapper() {
public Object mapRow() throws SQLException, DataAccessException {
Motorist motorist = new Motorist();
motorist.setId(rs.getInt(1));
motorist.setEmail(rs.getString(2));
motorist.setPassword(rs.getString(3));
motorist.setFirstName(rs.getString(4));
motorist.setLastName(rs.getString(5));
return motorist;
}
}
According the Spring documentation, RowMapper is an interface. It looks to me like an anonymous class definition based on the RowMapper interface. The new keyword is a little confusing, making me wonder if this also creates one instance of the anonymous class. I would guess yes, because if the class has no name, how will you ever create an instance after the line that defines it?
Can anyone confirm my guesses that:
this is an anonymous class definition based on the RowMapper interface, and
it creates a single instance of that class?
This is an anonymous class definition based on the RowMapper interface
That's precisely what it is.
It creates a single instance of that class?
Yep. That's correct.
That code is implementing the interface in an anonymous way.
The syntax would be similar to:
Runnable runnable = new Runnable() {
public void run() {
}
};
Note the semicolon at the end of the declaration. Here the runnable object, though holds the reference to the Runnable interface actually contains the implemented object. That's runtime polymorphism for you!
Your guesses are entirely correct. An anonymous class definition may be based on either a non-final class or on an interface, and you must implement all abstract (or interface) methods. The only available syntax for declaring anonymous classes is new, which also has the effect of instantiating exactly one instance of the anonymous class (in the course of the program, though, many instances of the same anonymous class could be created, if this code is executed several times).
Interface tells what methods the built class instance should have or if thy are label interfaces, then what kind of behavior to associate with it.
Anonymous classes are classes that basically while instantiating a class instance thy are also extending it with custom code. So if you are instantiating a interface, then you must write all the methods described with that interface, and as long as you do at least that much, then compiler will be happy. This is what is done here.
IS this is an anonymous class definition based on the RowMapper interface?
Yes. As you can see mapRow() function has been written. And if you debug the code you can see, that is not a class of an instance of interface, but class that extends interface. In case of abstract class or just class, it would be same - extended. So if class is final you cant write anonymous class for it.
Does it create a single instance of that class?
Well, it extends it and makes an instance of it. It will be single instance and any sequent call to it would result in a different class. If you debug the code, then you can even see different class names dynamically associated with it.
Solely from the code above and without knowing about RowMapper, all you can assume is that a new anonymous class based on RowMapper (which may be an interface or a class) is instantiated.
Declaring Anonymous class and in below example it creates two instances .
public class Multithread {
void test(){
new Runnable() {
#Override
public void run() {
System.out.println("1");
}
}.run();
new Runnable() {
#Override
public void run() {
System.out.println("11");
}
}.run();}
public static void main(String[] args) {
new Multithread().test();
}
}
I'm new to Java and have the following question regarding inner classes:
When implementing an inner class, do I need to declare its attributes and methods scope i.e. public, private, protected?
EDIT: With the absence of delegates (as in C#) could someone mention how best to implement a messaging system in Java that enables communication between multiple forms (Jframe)?
I have read that I can use inner classes for this but I'm also told I should not implement inner classes more than a few lines in size. Which school should I follow?
If you want to.
An inner class is roughly speaking like any other class. (Except that if you don't declare it static, it will have an EnclosingClass.this reference.)
I would suggest treating inner classes as private.
In Java, an outer class and all of its nested (including inner) classes can fiddle with each others privates. (The generated bytecode may be pointlessly verbose with additional synthetic access methods, but this is highly unlikely to matter.)
From an interface point of view, a class having weird inner class types is a bit weird. And more difficult to test if you are into that sort of thing. Too often nested type are created because creating a new file in a bad IDE is a bit of a pain - don't be tempted with nasty shortcuts.
Having said that inner classes are very useful. Use them with taste.
when implementing a inner class do i need to declare its attributes and methods scope i.e. public, private, protected?
It depends completely on how you wanted the inner class to behave.
By default, an inner class is non-static:
public class Example1
{
int a;
public class Example2
{
int b;
void test () {}
}
}
A non-static inner class can be instantiated only inside a non-static method of the outer class. This is because every instance of a non-static inner class must be associated with an instance of the outer class. In a sense, every instance of a non-static inner class exists ``inside'' an instance of the outer class. A single instance of the outer class may have associated with it more than one instance of the inner class.
Because an instance of a non-static inner class has an associated instance of the outer class, the methods of the inner class can access directly any of the members (fields or methods) of the outer class instance. For example, the test method defined above can access both a and b directly
A class defined within another class is called a nested class. Like other members of a class, a nested class can be declared static or not. A nonstatic nested class is called an inner class. An instance of an inner class can exist only within an instance of its enclosing class and has access to its enclosing class's members even if they are declared private.
The following table shows the types of nested classes:
Types of Nested Classes Type Scope Inner
static nested class member no
inner [non-static] class member yes
local class local yes
anonymous class only the point
where it is
defined yes
Although this is not an answer your question but make sure you are aware of the "static" modifier of inner classes.
public class Stuff {
public static class SubStuff {
//private or protected
}
}
Is different than this:
public class Stuff {
public class SubStuff {
//only private
}
}
If you have a static inner class than you might want protected variables, protected methods so on. But for inner classes that are not static generally you want everything private.
Google for the difference.
Inner can be seen by only the enclosing class. Its mostly used to achieve a utility function within the class. Lets use Door and Password as example.
public class Door {
public boolean isPassword(String key) {
//local inner class - its hidden from the world
class Password{
public boolean isPassword(String key) {
if(!key.equals("xyz")) {
System.out.println("Not Password. Door is locked");
return false;
}else {
System.out.println("Password corect. Door is opened");
return true;
}
}
}
return new Password().isPassword(key);
}
}