Overriding method while creating an object [duplicate] - java

This question already has answers here:
Java - Interface, instantiating an interface?
(3 answers)
Closed 7 years ago.
I came across a piece of code that I don't entirely understand.
There is an interface that is created within a class like this:
public class SomeClass {
public interface SomeInterface{
public String getInfo(String str1, String str2);
}
public static final SomeInterface SomeOtherName = new SomeInterface() {
#Override
public String getInfo(String str1, String str2){
//return something;
}
}
}
and then in another class they call the method getInfo using SomeOtherName. I don't understand what is going on here. To be honest I have not created an interface while in a class and then create an object of that interface type and then override methods in it. Can someone please explain me what is going on in this piece of code as I need to test it.

They are called as annonymous classes
They enable you to declare and instantiate a class at the same time.
Edit :
They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

SomeOtherName is an instance of an anonymous class that implements the SomeInterface interface.

Related

Why does the code can instantiate a java interface [duplicate]

This question already has answers here:
Java: Interface with new keyword how is that possible?
(9 answers)
Closed 8 months ago.
I understood that java interface cannot be instantiated. However, the below code looks like it instantiated an interface ? I'm trying to understand the code.
interface I{
int a();
int b();
}
public class C {
public static void main(String [] arg){
I i=(new I(){
public int a(){return 1;}
public int b(){return 2;}
});
assert i.a()==1 && i.b()==2;
}
}
An interface is like an all-abstract class, but that unambiguously supports multiple inheritance. You can instantiate any child of it that implements all the abstract methods.
The code you are asking about is creating an anonymous class that provides an implementation of all the abstract methods. Since the class is anonymous, the type of its instance can is most specifically given as I. Given that it's anonymous, that's also the only aspect of it you care about.

Java Interface two method with optional parameters [duplicate]

This question already has answers here:
Why should I ever overload methods?
(6 answers)
Closed 2 years ago.
I want to have an interface that allows me to use methods with optional parameters. Suppose I have an interface:
public interface Stuff {
public int Add();
}
And I have two classes A and B who implement the interface. One method needs parameter, but the other one doesn't.
public class CLASS A implements Stuff{
public int Add();
}
public class CLASS B implements Stuff{
public int Add(String name);
}
How can I achieve this?
I think You have to override function.
You can read about that here => https://www.geeksforgeeks.org/overriding-in-java/

Java curly braces after new [duplicate]

This question already has answers here:
Can we create an object of an interface?
(6 answers)
Closed 7 years ago.
Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
Is it correct here?
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A
{
}
public class B implements A
{
}
public static void main(String[] args)
{
A test = new B();
//A test = new A(); // wont compile
}
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.
Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:
interface ProgrammerInterview {
public void read();
}
class Website {
ProgrammerInterview p = new ProgrammerInterview() {
public void read() {
System.out.println("interface ProgrammerInterview class implementer");
}
};
}
This works fine. Was taken from this page:
http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Short answer...yes. You can use an anonymous class when you initialize a variable.
Take a look at this question: Anonymous vs named inner classes? - best practices?
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes it is correct. you can do it with an inner class.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc

How can we create object of interface in java? [duplicate]

This question already has answers here:
This appears to create an object from an interface; how does it work?
(4 answers)
Closed 9 years ago.
How is this code working i m totally puzzled....
package com.servletpack.examples;
interface check {
public void message();
}
public class Interface {
public static void main(String[] args) {
try {
check t = new check() {//how????????????????
public void message() {
System.out.println("Method defined in the interface");
}
};
t.message();
} catch (Exception ex) {
System.out.println("" + ex.getMessage());
}
}
}
With that syntax, you create an anonymous class, which is perfectly legal.
Internally, anonymous classes are compiled to a class of their own, called EnclosingClass$n where the enclosing class' name precedes the $ sign. and n increases for each additional anonymous class. This means that the following class is being created:
class Interface$1 implements check {
public void message() {
System.out.println("Method defined in the interface");
}
}
Then, the code in main compiles to internally use the newly-defined anonymous class:
check t = new Interface$1();
t.message();
It is anonymous class. Your check class is an interface. Anonymous class defines an implementation of given interface on the fly. So it saves you from creating a seperate class for Interface's implementation. This approach is only useful when you know you will never require this implementation any where else in the code.
Hope this explanation helps !!
You are creating an instance (on the fly) of anonymous class that implements the interface check.
Your interface reference can hold the object of the implementing class. You are implementing an anonymous class and assigning it to the reference of interface, which is absolutely legal in JAVA.

Java Abstract Methods [duplicate]

This question already has answers here:
Abstract methods in Java
(3 answers)
Closed 8 years ago.
I am slightly confused with the keyword abstract here. My compiler is telling me that I am not allowed to have a body for a method that's abstract. However my assignment says:
The abstract method orderDescription() returns a String giving details about a particular order.
abstract String orderDescription()
{
return null;
}
However my code returns an error, as I mentioned above. So my question is what should I do for this problem?
Up to now I've just removed the keyword abstract and it works fine.
abstract String orderDescription()
{
return null;
}
should be
abstract String orderDescription();
As error says, your abstract method declaration shouldn't contain any body.
Above syntax mandates the implementation (which ever class extends the abstract class and provides implementation) to return a String.
You can't instantiate abstract class, so some class need to extend abstract class and provide implementation for this abstract method.
Example:
class MyabsClass
{
abstract String orderDescription();
}
class MyImplementation extends MyabsClass
{
public String orderDescription()
{
return "This is description";
}
}
class MyClient
{
public static void main(String[] args)
{
MyImplementation imple = new MyImplementation();
imple.orderDescription();
}
}
When you define an abstract method, you are telling the compiler that any subclasses must provide an implementation (or also declare themselves abstract).
You implement the abstract method in a subclass.
Remember, you cannot create instances of abstract classes themselves. The entire point of an abstract method is to tell the compiler that you want subclasses to provide the functionality.
Essentially, an abstract function shouldn't contain any details, it is a placeholder function for inherited functions. As Nambari stated, you should only include the definition.
This is used for when you want a family of classes to all contain a common function, which you wish each child class to define.
Abstract methods generally shouldn't contain any "real" code, abstract methods are to be overidden by non-abstract classes containing the method.
Abstract method should not have any method body. It allows only method declaration.
Also, adding to Nambari's example, what you can do is
class MyabsClass
{
abstract String orderDescription();
}
class MyClient
{
public static void main(String[] args)
{
MyabsClass mac = new MyabsClass(){
public String orderDescription()
{
return "This is description";
}
};
mac.orderDescription();
}
}
That is, through anonymous class.

Categories

Resources