When I tried to do some sample on an abstract class in Java I accidentally got some thing like anonymous inner class in Eclipse.
I have pasted the piece of code below. I don't understand how the abstract class is related to anonymous class.
package com.Demo;
abstract class OuterClass {
abstract void OuterClassMethod();
}
public abstract class InnerClass extends OuterClass {
public static void main(String[] args) {
InnerClass myInnerClass = new InnerClass() {
#Override
void OuterClassMethod() {
int OuterClassVariable = 10;
System.out.println("OuterClassVariable" + " " + OuterClassVariable);
}
};
}
}
A anonymous class is an "in-line" concrete implementation of a class, typically (but not necessarily) of an abstract class or an interface. It is technically a subclass of the extended/implemented super class.
Google for more.
In your example, your class (InnerClass) extends class (OuterClass) and implementing their abstract methods which is the typical behavior of extending an abstract class. In the same way if your class implementing any interfaces you have to override their abstract methods. This is the way to implement Anonymous inner class.
Basically, an anonymous class is an implementation that has no name -- hence the "anonymous" bit.
This particular bit is what makes your class anonymous:
InnerClass myInnerClass = new InnerClass() {
#Override
void OuterClassMethod() {
int OuterClassVariable = 10;
System.out.println("OuterClassVariable" + " " + OuterClassVariable);
}
};
In normal class instantiations, you would just use:
InnerClass myInnerClass = new InnerClass();
but in this case, you are specifying a new implementation of that class, by overriding a function (OuterClassMethod()) within it. In other instances of InnerClass, OuterClassMethod() will still have its original implementation, because you only adapted this particular instance of InnerClass, and did not store this new implementation in a new class.
If you don't want anonymous classes, do this instead:
Somewhere, specify AnotherInnerClass to extend InnerClass, and to override that function:
class AnotherInnerClass extends InnerClass {
#Override
void OuterClassMethod() {
int OuterClassVariable = 10;
System.out.println("OuterClassVariable" + " " + OuterClassVariable);
}
};
And then instantiate it as such:
AnotherInnerClass myInnerClass = new AnotherInnerClass();
Related
I am starting java programming and I came across abstract classes. I know that you cannot instantiate them without creating concrete classes which extend them to become the subclass. However, I got really confused when I tried this code and it runs ok.
abstract class Communication{
public void FirstMethod()
{
System.out.println("I am first method()\n");
}
}
public class Main{
public static void main(String[] args){
Communication communication = new Communication() {
#Override
public void FirstMethod(){
super.FirstMethod();
}
};
communication.FisrtMethod();
}
}
Output is: I am first method().
If I modify it to:
Communication communication = new Communication() {
#Override
public void FirstMethod(){
System.out.println("I've been called from Main");
}
};
The output is: I've been called from Main.
Could somebody please explain if this is a kind of instantiation or what concept is this?
This is termed as
Anonymous Class
Definition:
An inner class declared without a class name is known as an anonymous inner class.
In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface.
This is called anonymous inner class. This way you can implement an interface or abstract class without having to find a name for it and instantiate it at the same time. This concept is useful when you use a certain implementation just once.
The construct looks always like that:
new SomeClass() {
//implementation of methods
};
This is known as anonymous class. The anonymous class definition allows you to provide a class definition within code and it has no formal name. The anonymous class expression has the class definition and instance creation expression.This is not limited to abstract classes but also for interfaces and concrete classes.
For example
abstract class A { }
// so the anonymous class expression is
A a = new A() {// class definition };
// This will actually create an instance of a
// class that extends the abstract class A
// that java will create at run time
You can even use anonymous class expression in the method arguments.Example of this is a Comparator in Collections.sort() method;
Collections.sort(listOfValues,new Comparator<Value>(){
public int compare(Value v1, Value v2){
// method implemetation.
}
})
I recently saw implementing where a interface is implemented in a class and in another class we have a static final variable of the interface type and it somehow was able to complete computation from the class that had implemented the interface .
My question is how will the interface variable handle this if more than one class has a implementation of the interface. Am I missing something or it is just guessing where the implementation of interface is .
This is for java language
public interface DemoMe{
public void doSomething();
}
public class MainClass implements demoMe {
public void doSomething(){
System.out.println("Something was done ");
}
}
public class AnotherClass {
private final DemoMe demoVariable;
public void useMe(){
demoVariable.doSomething();
}
}
here the AnotherClass somehow knows how to look for implementation of doSomething. can someone point me towards how this exactly works.
The variables in java interface are public static and final type. You whenever a class implements an interface. The interface variable become part of the class. Now these variable can be accessed using class reference or object reference. These variable are final so cannot be updated and static so always belong to the class. The interface itself need not to manage anything. The implementing class will take care of it.
Here we have defined an interface DemoMe with one method and one variable. Now DemoMeOne class implements the interface. The need to provide the definition for methods coming from interface. The doSomething() method simply prints a statement an access the variable from interface. Now we define an other class which instantiate the DemoMeOne class and access the interface method and variable.
interface DemoMe{
public void doSomething();
public int variable = 100;
}
class DemoMeOne implements DemoMe {
public void doSomething(){
System.out.println("Something was done.");
System.out.println("Access interface variable: " + variable);
}
}
class MainClass {
public static void main(String[] args) {
DemoMeOne demoMeOne = new DemoMeOne();
System.out.println("Variable from interface using DemoMeOnce class: " + DemoMeOne.variable);
System.out.println("Variable from interface using DemoMeOnce object reference: " + demoMeOne.variable);
System.out.println("Variable from interface using interface itself: " + DemoMe.variable);
demoMeOne.doSomething();
}
}
output:
Variable from interface using DemoMeOnce class: 100
Variable from interface using DemoMeOnce object reference: 100
Variable from interface using interface itself: 100
Something was done.
Access interface variable: 100
The below example I had seen in oracle doc for anonymous classes example.But how they can write interface HelloWorld inside a class HelloWorldAnonymousClasses
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public void sayHello() {
class EnglishGreeting implements HelloWorld {
String name = "world";
public void greet() {
greetSomeone("world");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
HelloWorld englishGreeting = new EnglishGreeting();
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
HelloWorld spanishGreeting = new HelloWorld() {
String name = "mundo";
public void greet() {
greetSomeone("mundo");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hola, " + name);
}
};
englishGreeting.greet();
frenchGreeting.greetSomeone("Fred");
spanishGreeting.greet();
}
public static void main(String... args) {
HelloWorldAnonymousClasses myApp =
new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
Interfaces can be anonymously implemented. This will not be an implementation of the interface, but rather the implementation of an interface in an anonymous subclass.
The interface itself doesn't get instantiated.
The line in question is this:
HelloWorld frenchGreeting = new HelloWorld() {
where HelloWorld is an interface. The curly brackets already indicate that this is an anonymous class. By defining it as HelloWorld you force the anonymous class to implement the methods defined in the interface.
If you are referring to the interface itself being defined inside class: if you want to have an interface defined for only the current class without exposing it to other objects, you can define it inside your class.
If you want to make it available to the outside world as well, you'll have to declare your class and interface public and access it using MyClass.MyInterface.
You can declare nested interfaces in the same way as you can declare static nested classes and inner classes. A nested interface declaration is implicitly static (Java Language Specification §8.5.1) - an "inner interface" wouldn't make sense because every instance of an inner class holds a reference to the relevant instance of the containing class, and you can't create an instance of an interface (only of a class that implements the interface).
In your example the interface definition has default visibility (it isn't declared public, protected or private) so any class that is in the same package as HelloWorldAnonymousClasses could refer to the nested interface as HelloWorldAnonymousClasses.HelloWorld.
There may be a scenario, where you need multiple implementations of a interface inside a class(and only to that class, you don't want to expose), so Java provides feature of declaring Interface inside class.
You can refer here, similar question.
If you read the tutorial trail a little farther, it actually can answer your question.
An anonymous class definition is an expression, it must be part of a statement. The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.
The instantiation of the frenchGreeting object in your example:
HelloWorld frenchGreeting = new HelloWorld() { /* other code */ };
The anonymous class expression is part of the statement that instantiates the frenchGreeting object, ended by a semicolon after the closing brace. the anonymous class is implementing the interface HelloWorld. When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
Can we have a class inside an interface which has different methods of the interface implemented in it. I have a doubt here that why Java allows writing Inner classes inside interfaces and where can we use it.
In the program below I have written a class inside Interface and implemented the methods of the interface. In the implementation class of the interface I have just called the inner class methods.
public interface StrangeInterface
{
int a=10;int b=5;
void add();
void sub();
class Inner
{
void add()
{
int c=a+b;
System.out.println("After Addition:"+c);
}
void sub()
{
int c=a-b;
System.out.println("After Subtraction:"+c);
}
}
}
abstract public class StrangeInterfaceImpl implements I {
public static void main(String args[])
{
StrangInterface.Inner i=new StrangeInterface.Inner();
i.add();
i.sub();
}
}
You can define a class inside an interface. Inside the interface, the inner class is implicitly public static.
From JLS Section 9.1.4:
The body of an interface may declare members of the interface, that is, fields (§9.3), methods (§9.4), classes (§9.5), and interfaces (§9.5).
From JLS Section 9.5:
Interfaces may contain member type declarations (§8.5).
A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.
The only restriction on the inner class defined inside the interface or any other class, for that matter, is that, you have to access them using the enclosing member name.
Apart from that, there is no relation between them. The inner class will result in completely a different class file after compilation.
For e.g., if you compile the following source file:
interface Hello {
class HelloInner {
}
}
Two class files will be generated:
Hello.class
Hello$HelloInner.class
Can we have a class inside an interface which has different methods of the interface implemented in it.
IMHO But interfaces are not meant to for that purpose.
If you write inner class in an interface it is always public and static.
It's equivalent to
public interface StrangeInterface
{
public static class Inner{
}
and the variable inside the interface also explicitly public static variables.
An interface might provide its own implementation as a default.
Note that unless you declare the inner class implements the interface, there's no relation between the two other than it's an inner class. When a class is very tightly related to the interface this isn't intrinsically unreasonable, although I'd be suspicious it's a generally-useful pattern.
to summarize "where can we use it" by defining a class inside an interface:
1. to provide default implementation for an interface
2. if argument or return type for interface method/s is class
w.r.t your code
interface StrangeInterface {
int a = 10;
int b = 5;
void add();
void sub();
class Inner implements StrangeInterface {
public void add() {
int c = a + b;
System.out.println("After Addition:" + c);
}
public void sub() {
int c = a - b;
System.out.println("After Subtraction:" + c);
}
}
}
class MyTest implements StrangeInterface {
public void add() {
System.out.println("My own implementation for add : " + (a +b));
}
public void sub() {
System.out.println("My own implementation for sub : " + (a- b));
}
}
public class StrangeInterfaceImpl {
public static void main(String args[]) {
StrangeInterface.Inner i = new StrangeInterface.Inner(); // calling default implementation
i.add();
i.sub();
MyTest t = new MyTest(); // my own implementation
t.add();
t.sub();
}
}
How do I create an object of an abstract class and interface? I know we can't instantiate an object of an abstract class directly.
You can not instantiate an abstract class or an interface - you can instantiate one of their subclasses/implementers.
Examples of such a thing are typical in the use of Java Collections.
List<String> stringList = new ArrayList<String>();
You are using the interface type List<T> as the type, but the instance itself is an ArrayList<T>.
To create object of an abstract class just use new just like creating objects of other non abstract classes with just one small difference, as follows:
package com.my.test;
public abstract class MyAbstractClass {
private String name;
public MyAbstractClass(String name)
{
this.name = name;
}
public String getName(){
return this.name;
}
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyAbstractClass ABC = new MyAbstractClass("name") {
};
System.out.println(ABC.getName());
}
}
In the same way You can create an object of interface type, just as follows:
package com.my.test;
public interface MyInterface {
void doSome();
public abstract void go();
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyInterface myInterface = new MyInterface() {
#Override
public void go() {
System.out.println("Go ...");
}
#Override
public void doSome() {
System.out.println("Do ...");
}
};
myInterface.doSome();
myInterface.go();
}
}
There are two ways you can achieve this.
1) Either you extend / implement the Abstract class / interface in a new class, create the object of this new class and then use this object as per your need.
2) The Compiler allows you to create anonymous objects of the interfaces in your code.
For eg. ( new Runnable() { ... } );
Hope this helps.
Regards,
Mahendra Liya.
You can provide an implementation as an anonymous class:
new SomeInterface() {
public void foo(){
// an implementation of an interface method
}
};
Likewise, an anonymous class can extend a parent class instead of implementing an interface (but it can't do both).
public abstract class Foo { public abstract void foo(); }
public interface Bar { public void bar(); }
public class Winner extends Foo implements Bar {
#Override public void foo() { }
#Override public void bar() { }
}
new Winner(); // OK
"instantiate" means "create an object of".
So you can't create one directly.
The purpose of interfaces and abstract classes is to describe the behaviour of some concrete class that implements the interface or extends the abstract class.
A class that implements an interface can be used by other code that only knows about the interface, which helps you to separate responsibilities, and be clear about what you want from the object. (The calling code will only know that the object can do anything specified in the interface; it will not know about any other methods it has.)
If you are using someone else's code that expects a Fooable (where that is the name of some interface), you are not really being asked for an object of some Fooable class (because there isn't really such a class). You are only being asked for an instance of some class that implements Fooable, i.e. which declares that it can do all the things in that interface. In short, something that "can be Foo'd".
You write a class that derives from the abstract class or implements the interface, and then instantiate that.
What you know is correct. You cannot create an object of abstract class or interface since they are incomplete class (interface is not even considered as a class.)
What you can do is to implement a subclass of abstract class which, of course, must not be abstract. For interface, you must create a class which implement the interface and implement bodies of interface methods.
Here are orginal tutorial on oracle site, http://download.oracle.com/javase/tutorial/java/IandI/abstract.html and http://download.oracle.com/javase/tutorial/java/concepts/interface.html
You can not instantiate the abstract class or an interface, but you can instantiate one of their subclasses/implementers.
You can't instantiate an abstract class or an interface, you can only instantiate one of their derived classes.
In your example
MyAbstractClass ABC = new MyAbstractClass("name") {
};
You are instantiating any class that implements Suprising.
public abstract class AbstractClass { ... }
public interface InterfaceClass { ... }
// This is the concrete class that extends the abstract class above and
// implements the interface above. You will have to make sure that you implement
// any abstract methods from the AbstractClass and implement all method definitions
// from the InterfaceClass
public class Foo extends AbstractClass implements InterfaceClass { ... }
NO, we can't create object out of an interface or Abstract class because
Main intention of creating an object is to utilize the wrapped methods and data.
As interface don't have any concrete implementation hence we cannot.
For abstract class we may have concrete method or abstract method or both.
There is no way for the API developer to restrict the use of the method thats don't have implementation.
Hope help.
No, you are not creating the instance of your abstract class here. Rather you are creating an instance of an anonymous subclass of your abstract class. And then you are invoking the method on your abstract class reference pointing to subclass object.