How is the interface being instantiated, without implementation of any class? [duplicate] - java

This question already has answers here:
Can we create an instance of an interface in Java? [duplicate]
(7 answers)
Closed 2 years ago.
public interface InterfaceTest {
interface Gift { void present(); }
interface Guest { void present(); }
interface Presentable extends Gift, Guest { }
public static void main(String[] args) {
Presentable johnny = new Presentable() {
#Override public void present() {
System.out.println("Heeeereee's Johnny!!!");
}
};
johnny.present();
((Gift) johnny).present();
((Guest) johnny).present();
Gift johnnyAsGift = (Gift) johnny;
johnnyAsGift.present();
Guest johnnyAsGuest = (Guest) johnny;
johnnyAsGuest.present();
}
}
This code compiles and runs the main() function without error, what concept am I missing here?

johnny is an instance of an anonymous subclass. From the link:
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. Use them
if you need to use a local class only once.
The reason your code compiles is because the implementation of present is provided in this anonymous subclass. To drive the point further, this:
Presentable johnny = new Presentable();
would not compile. However, this:
Presentable johnny = new Presentable() {
#Override public void present() {
// Do something
}
};
is perfectly valid.

Related

Where to write the common logic in Java Strategy design pattern? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
Improve this question
This is related to Java Strategy design pattern.
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object.
I have common code logic to be executed for all the strategies which is have implemented using Java Strategy design pattern. Which is the right place to write this common logics(something like validations and other stuffs).
Consider the below code. Here I want to do file validation which is common across any file type . Something like , the file should exist and its size should be greater than zero and file name validation. All these file related common stuff I want to keep in some place. Which could be a right design for this?
//BaseFileParser.java
public abstract class BaseFileParser{
public abstract void parseFile();
}
//XMLFileParser.java
public class XMLFileParser extends BaseFileParser{
public void parseFile(){
//Logic for parsing an XML file goes here
}
}
//CSVFileParser.java
public class CSVFileParser extends BaseFileParser{
public void parseFile(){
//Logic for parsing a CSV file goes here
}
}
//Client.java
public class Client{
private BaseFileParser baseFileParser;
public Client(BaseFileParser baseFileParser){
this.baseFileParser=baseFileParser;
}
public void parseFile(){
baseFileParser.parseFile();
}
public static void main(String args[]){
//Lets say the client needs to parse an XML file
//The file type(XML/CSV) can also be taken as
//input from command line args[]
Client client=new Client(new XMLFileParser());
client.parseFile();
}
}
If you have common behaviour, then abstract class or class is what we can use. So basic idea is to put common logic into some base common strategy class. Then we should create abstract method in abstract class. Why? By doing this, subclasses will have particular logic for concrete strategy.
I am sorry, I am not Java guy, but I've provided comments how it can be implemented in Java. Let me show an example via C#.
This is our abstract class which has common strategy:
public abstract class BaseStrategy
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public void CommonBehaviourHere()
{ }
public abstract void
UnCommonBehaviourHereShouldBeImplementedBySubclass();
}
And its concrete implementations:
public class StrategyOneSubclass : BaseStrategy // extends in Java
{
public override void
UnCommonBehaviourHereShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
public override void
UnCommonBehaviourHereShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
UPDATE:
This is your abstract class:
public abstract class BaseFileParser
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public bool IsValid()
{
return true;
}
public abstract void ParseFile();
}
and its concrete implementations:
public class StrategyOneSubclass : BaseStrategy // extends in Java
{
public override void ParseFile()
{
if (!IsValid())
return;
throw new NotImplementedException();
}
}
public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
public override void ParseFile()
{
if (!IsValid())
return;
throw new NotImplementedException();
}
}

c# Anonymous Interface Implementation [duplicate]

This question already has answers here:
C# equivalent of creating anonymous class that implements an interface
(2 answers)
Closed 4 years ago.
i've already seen this question a few times but i still don't get it.
In Java, i can do this:
new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Hello");
}
}).start();
In my opinion, this is a very nice way to implement interfaces which implementations are only used once. Is there a way to do this in C#?
I've already heard of delegates, but that only solves the problems partly since i can only implement one method. What is the "right" way to do that in C# if i have multiple methods? Do i have to implement another class for that?
Thanks in Advance!
-Chris
EDIT:
I don't want to make a new thread specifically. That was a more general question about the right way to do something like an anonymous implementation from Java in C#. It's not about that specific example.
The general way to do this is C# is to create your own private class. As you noted, other approaches in C# (delegate/lambda) only work when the interface has just one method (i.e., a Java functional interface):
Java:
void testMethod()
{
x = new ISomeInterface(){
#Override
public void method1() { foo(); }
#Override
public void method2() { bar(); }
};
}
C#:
void testMethod()
{
x = new ISomeInterfaceAnonymousInnerClass();
}
private class ISomeInterfaceAnonymousInnerClass : ISomeInterface
{
public void method1()
{
foo();
}
public void method2()
{
bar();
}
}
Here is the simplest conversion when a Java functional interface is involved:
Java:
#FunctionalInterface
interface ISomeInterface
{
void method();
}
void testMethod()
{
x = new ISomeInterface(){
#Override
public void method() { foo(); }
};
}
C#:
delegate void ISomeInterface();
void testMethod()
{
x = () =>
{
foo();
};
}
Probably you've searched this before and by now the answer is: No. Noway in C#
But I think your main question is Why?
Short Answer: It can be designed in the next C# versions as a feature. It's absolutely possible.
Long Answer: If you want more details on why it's not added to the C# yet; there is a helpful conversation below this exact feature request in the Roslyn (an open-source .Net complier) page at GitHub. Check it out: https://github.com/dotnet/roslyn/issues/13

How to declare a method that returns an instance of an interface

So I am a bit new to Java. I just got introduced to interfaces and i have to create a method that returns an instance of the interface Chassis
Below is the code:
public interface Chassis {
public String Chassis = "Chassis";
public static void main(String[] args) {
public String getChassisType() {
return Chassis;
}
The problem is, I keep getting error that abstract methods cannot have a body (as indicated by the blockquote) yet i had not declared my method as abstract.
What seems to be the problem?
You have two problems, You can't put a method inside another method, and you can't define a method like this in an interface in Java. In Java 8 you can do this
public interface Chassis {
String Chassis = "Chassis";
default String getChassisType(){
return Chassis;
}
}
I wouldn't define your public static void main inside an interface. While it is allowed now, most developers would find this confusing. See #Jürgen's answer, as this what most experienced developers would say I believe.
I would create another class like
public class Main {
public static void main(String... args) {
// an anonymous subclass so you have something to create/call.
System.out.println(new Chassis(){}.getChassisType());
}
}
An interface is a kind of abstract. It cannot be instantiated, It can have only declaration of methods and attributes not definition. You can only implement it in a class, if you do so in a class you must define all the methods which are declared in the interface. A main method need to be defined in order to execute the program. So it should not be placed inside an interface. change your code like this below
public interface chassis
{
String Chassis;
public String chassis();
}
public class example implements chassis
{
public String chassis()
{
Chassis="chassis";
return Chassis;
}
public static void main(String[] args)
{
System.out.println(new example().getChassisType());
}
}
This code would not work at all. A main method is only valid for classes, not for interfaces.
EDIT: as stated below the answer is not correct. But having a method inside a method still does not work. See the other answers.

Code Snippet involving Inheritance [duplicate]

This question already has answers here:
Using inherited overloaded methods
(11 answers)
Closed 7 years ago.
The code I am running is as follows :
public class Triangle {
public void draw() {
System.out.println("Base::draw\n");
}
public void computeCentroid(Triangle t) {
System.out.println("Base::centroid");
}
}
class RightAngledTr extends Triangle {
public void draw() {
System.out.println("RightAngle::draw\n" );
}
public void computeCentroid(RightAngledTr t) {
System.out.println("RtAngle::centroid");
}
}
public static void main(String[] args) {
Triangle tr= new RightAngledTr();
RightAngledTr rtr= new RightAngledTr();
tr.computeCentroid(tr);
tr.draw();
tr.computeCentroid(rtr);
}
The output this gives is as follows :
Base::centroid
RightAngle::draw
Base::centroid
I don't understand the reason behind the third output line.
My doubt :
tr.computeCentroid(rtr) should call the method of Derived class RightAngledTr(since the parameter passed is rtr). Hence print : RtAngle::centroid
Please help me out here. Thanks in advance!
public void computeCentroid(RightAngledTr t)
and
public void computeCentroid(Triangle t)
have different method signatures, so there is no override here, at all.
Class RightAngledTr does not override the method but overload since Java method is invariant.
Class RightAngledTr has 2 methods essentially, one requiring Triangle and the other RightAngledTr) so by specifying the most specific parameter, the JVM knows which methods to invoke by matching the parameter type to the most specific method matching it.
See more:
JLS 15.12.2.5. Choosing the Most Specific Method
For RightAngledTr.computeCentroid to override Triangle.computeCentroid it must have a matching parameter declaration. But yours does not. If you change your declaration in RightAngledTr to:
#Override
public void computeCentroid(Triangle t)
Then you will see the behavior you expect. Note the use of #Override, which will help you identify this issue in the future.

How to access method from two classes which do not share an interface?

I am creating a java library that will access web services, but the library will be called in different platforms, so we are using ksoap2 and ksoap2-android to generate helper classes for the different platforms. The problem is that we then have two sets of generated classes/methods whose signatures are equivalent, but which do not overtly share a Java Interface - so I can't figure a way to call them from my main code.
A simplified example:
//generated for Android
class A {
public String sayHi() {
return "Hi A";
}
}
//generated for j2se
class B {
public String sayHi() {
return "Hi B";
}
}
//main code - don't know how to do this
XXX talker = TalkerFactory.getInstance()
String greeting = talker.sayHi()
Of course, that last part is pseudo-code. Specifically, how can I call sayHi() on an instance of an object which I don't know the type of at compile time, and which does not conform to a specific interface? My hope is that there is some way to do this without hand editing all of the generated classes to add an "implements iTalker".
The straightforward way is to use an adapter.
interface Hi {
void sayHi();
}
public static Hi asHi(final A target) {
return new Hi() { public void sayHi() { // More concise from Java SE 8...
target.sayHi();
}};
}
public static Hi asHi(final B target) {
return new Hi() { public void sayHi() { // More concise from Java SE 8...
target.sayHi();
}};
}
In some circumstance it may be possible, but probably a bad idea and certainly less flexible, to subclass and add in the interface.
public class HiA extends A implements Hi {
}
public class HiB extends B implements Hi {
}

Categories