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.
Related
I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.
C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.
This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.
If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.
you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.
In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :
interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString(){
return "test";
}
});
}
}
In java, You can never instantiate an interface in java. But why the above code prints "test" as output instead of raising an error ?
Because you are not instantiating an interface but defining (and instantiating at the same time) a new class, so a new type, which implements TestA but it has no name.
That's an anonymous class.
Since you are having an interface, normally you would be having a class which will implement that interface like this.
class TestAImp implements TestA {
//Some other Code
String toString(){
return "test";
}
}
And to use this object you will be doing something like this
public class Test {
public static void main(String[] args) {
System.out.println(new TestAImp().toString());
}
}
Now suppose for some purpose you decide not to declare a class which implements that interface, but you want to implement that interface. This is where anonymous classes come into picture. In the case of anonymous class you don't write the code of that class in some file .java but instead write the code of that class while creating the object itself.
Since your interface has only one method, you can create anonymous classes, like this. I am declaring 2 classes Test and Test2 which have 2 different implementations of the interface.
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString(){
return "test1";
}
});
}
}
public class Test2 {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString(){
return "test2";
}
});
}
}
The difference is not between the notations you have in your title. The difference is that you are creating an anonymous class that implements the interface. That is completely legal. The notation may look a bit strange but when you get used to it you will have no problems with it.
This is an anonymous class definition based on the TestA interface
You created an anonymous class for it. The object created of this anonymous class will be implementing Test. And it will be passed to println(...) function.
Which will later call toString() method of the passed object and print returned value on screen. And that's why it prints "test";
I am trying to create an Anonymous class during which I came across following problem. In the following code when I change display method access modifier to default it gives an error but when I change it to public it works fine. Could you explain it to me why this happens.AFAIK public and default are work in similar as long as all classes are in same package. Please correct me if I am wrong.
//from file : Skg.java
package sandeep2;
class Skg1
{
public void display()
{
System.out.println("sandeep here");
}
}
class Skg2 {
public void say()
{
System.out.println("Skg2");
}
Skg1 obj = new Skg1()
{
**public void display()** //wont work if this is not public ????????????
{
System.out.println("I am ANONymous");
}
};
}
public class Skg {
public static void main(String[] args)
{
Skg2 x = new Skg2();
x.obj.display();
}
}
Class Skg2 attempts to create an instance of an anonymous inner class as a subclass of class Skg1. That anonymous inner class overrides Skg1.display(), which is public. You cannot override a method to reduce its visibility. Java does not permit it, and it would violate the substitution principle if you could do it.
I have a class called "Design", and I am writing the following code to extend the class to include a new function called sayHello(). However it doesnt seem to be working. Am I only allowed to ovveride existing functions in that way?
Design design1 = new Design() {
public void sayHello() {
System.out.println("hello");
}
};
design1.sayHello(); // this gives an error "function not found"
So that is logical.
You are overriding a super class and assigning it to the instance variable of super class.
As the instance variable is of super class type, you can access only those methods which are available in super class.
You can do that if your "Design" class is an interface. You could create an anonymous inner class.
Example:
public interface Design{
public void sayHello();
}
public class Test
{
public static void main(String args[])
{
Design d = new Design(){
#Override
public void sayHello(){
return "Hello World!";
}
};
System.out.println(d.sayHello());
}
}
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.