New function declaration inline in a java subclass - java

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

Related

Calling a method of abstract class from a concrete class without extending

Example abstract class is bellow.
public abstract class Vehicle {
void maintain(String str) {
System.out.println(str);
}
}
Example concrete class is bellow.
public class Driver {
public static void main(String[] args) {
}
}
Now I need to access the maintain method without extending the Vehicle class.Is there any way to do this without using static content?
No, there isn't, because maintain is an instance method. To call an instance method, you must have an instance. You can't create an instance of an abstract class.
You can subclass it anonymously (see this tutorial), but you still need to subclass it.
You can use an anonymous inner class. I've used your example code but also defined an anstract method in Vehicle
public class AbstractTest {
public static void main(String[] args){
Vehicle v = new Vehicle() {
#Override
void myOtherAbstractMethod() {
// Do what you need here
}
};
v.maintain("foo");
}
public static abstract class Vehicle {
void maintain(String str) {
System.out.println(str);
}
abstract void myOtherAbstractMethod();
}
}
You cannot do that as abstract classes are abstract. Also in your case there's no connection between Driver and Vehicle so even if you would be able to compile that code (you won't), then ClassCastException would show up.
You must extend abstract class first, like it or not.

Java Anonymous Class - minimal example

I'm trying to understand Java anonymous classes.
Looking here:
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
And here:
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm
I understand the basic syntax, but the examples are non-minimal.
What are the absolute minimal requirements to define a anonymous class in Java?
Edit>>>
Essentially this:
public class MyClass {
InnerClass instance = new InnerClass();
public class InnerClass{
public void print(){
System.out.println("First Call");
}
};
public void redefineInstance(){
instance = new InnerClass(){
public void print(){
System.out.println("Second Call");
}
};
}
public static void main(String[] args) throws Exception{
MyClass myobject = new MyClass();
myobject.instance.print();
myobject.redefineInstance();
myobject.instance.print();
}
}
The most minimal example:
interface Foo {}
public static void main (String[] args)
{
Foo foo = new Foo() {};
}
Literally a declaration of an interface, and then usage as an anonymous class with no additional declarations.
Practically speaking, it does nothing. However, as we add bits in:
interface Foo {
public void bar();
}
public static void main (String[] args) throws java.lang.Exception
{
Foo foo = new Foo() {
public void bar() {
System.out.println("Hello");
}
};
}
It becomes a full-fledged helper class for our method.
The most common use for early/mid level programming would be overriding Listeners to do specific actions. We know the Listener is listening for something, and we want it to do something as a result of the Listener, so we craft the Listener and say "Do this when you are triggered."
Here's the example of a really complex ActionListener tutorial: https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
But typically, if it's something that's mundane like "run a method on click", you'll use an anonymous in-line declaration that just calls a method for you.
I suppose the "absolute minimal requirement" to create an anonymous class is to have a place in your code that requires an instance of a non-final class or interface of some kind.
Meaning, if I have a method in MyClass:
public static void gimmeMyObject(MyObject c)
I can define an anonymous class that extends MyObject as long as MyObject is not final:
//Somewhere in a method
MyClass.gimmeMyObject(new MyObject() {
public String myMethod() {
return "I'm anonymous";
}
});
That anonymous class will be passed in as a MyObject.
However, I could not do this if the method required a String or Integer, for example, because those are final classes.
For the above example, the non-anonymous class would translate to:
public class MyAnonObject extends MyObject { //In actuality, an anonymous class doesn't have a name, though.
public String myMethod() {
return "I'm anonymous";
}
}
As Compass has already said, the absolute minimum is not useful.
Following is an example of a 'useful' inner class:
JButton ok = new JButton();
ok.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("abc");
}
});
So instead of having to define an inner class or a helper class for an ActionListener you only use once, you can just have it as an inline or anonymous class to remove clutter and increase readability.
How about this example?
//interface
interface Message{
String greet();
}
Message is a anonymous class in this example,
greet() is the only method inside this anonymous class.
//Passing an anonymous inner class as an argument
obj.displayMessage(new Message(){
public String greet(){
return "Hello";
}
});
You can think of an anonymous class as just basically the instantiation part of creating a new instance of an object. You essentially just don't declare it and give it a name. This is normally passed into method parameters as shown below.
Object someObj; is an object declaration.
someObj = new Objct(parm a,...) is the instantiation of the object.
//example of anonymous classes:
public void foo(Bar barObj){// takes a Bar object parameter
//does stuff
}
//you can call the foo method in this way
Bar barObject= new Bar();
foo(barObject){}
// or you can call the Bar anonymously
foo(new Bar()){}
In the anonymous example you instantiate a new Bar inside the method parameter. You can do this when you just need something local and don't need it to be used anywhere but in that method call. it also then gives you access to the accessible methods that are inside of the anonymous class. so you could do something like
foo(new Bar().barMethod){}. It just kind of depends what you are working with.

C# vs JAVA instance of Interface

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 :

In Java, what is the difference between new TestA() and TestA obj = new TestA()?

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";

Program will give an error if method not marked public ( all classes are in the same file)

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.

Categories

Resources