Anonymous classes having interface keyword inside a class declaration - java

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.

Related

Abstract class 'instantiation' with a body of its methods

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.
}
})

Learning a little about using interface variable

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

Clarification on Interface concept

interface A
{
public void printValue();
}
public class Test
{
public static void main (String[] args)
{
A a1 = new A() {
public void printValue()
{
System.out.println("A");
}
};
a1.printValue();
}
}
We cannot create an instance of an interface, but what is new A() doing in this code? I have seen this type of code used mostly with Comparators. Please explain.
new A() {} is an instantiation of an anonymous class that implements interface A.
It is a short-cut that can be useful if you need an instance of a class that implements an interface only in one place, so you don't want to define a normal class. This way you define the class at the same place it is being used.
In your code sample, it doesn't seem very useful, but usually it is used by passing the anonymous class instance to some method that accepts a parameter of the type of the interface.
new A() in below is where you are instantiating a concrete class (which we say anonymous) which implements the interface A
A a1 = new A() {
public void printValue(){
System.out.println("A");
}
};
In your code, interface A is used as an Anonymous class. You can use them if you need to use a local class only once. it's more over same as lambda expressions.
Read more: http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Read about lambda expression: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

Android instantiating and overriding pattern

I do not think this kind of OOP pattern exist in C#.net and C++. So what is the name of this pattern or feature. I encountered this when programming Android, is this a feature of Java too or not? Note : I know #Override is specific for android compiler/ide only.
Foo bar = new Foo(){
#Override
public void fighters(){
//some stuff
}
};
Is this somekind of Lambda thing?
Thanks!
This is example of inner class in Java. This is an anonymous inner class, where
An anonymous class is an inner class that does not have a name at all. And whose instance is being created at the time of its creation.
Read the Anonymous Classes documentation for more detail. And Override is Java annotation (not specific to Android). Read When do you use Java's #Override annotation and why?
Consider the example below
Let, you declare an interface HelloWorld like below.
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
And you want to write a class which extends HelloWorld
class TestClass implements HelloWorld {
String name = "world";
#Override
public void greet() {
greetSomeone("world");
}
#Override
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
and instantiate it as
TestClass testClass = new TestClass();
Here instead-of above two steps (declaring a class and instantiate it), you can just declare an anonymous inner class, like
HelloWorld testClass = new HelloWorld() {
String name = "world";
#Override
public void greet() {
greetSomeone("world");
}
#Override
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
};
here testClass is an object of an anonymous inner class which implements HelloWorld.

Inner classes inside Interface

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

Categories

Resources