Java: Interface reference? - java

We all know that you can't instantiate an interface in Java (directly at least).
But with something like this:
public class Test{
public interface Link {
void mySamplemethod();
String myString ="HELLO!";
}
public static void main(String []args){
Link b;
}
}
What exactly is b... and how could it ever have a practical purpose?

b is a variable of type Link that has no value, not even null. In order to have a practical purpose you must initialize it with an object reference whose class implements Link interface.
If you want to initialize Link with a non-null value, you should create a class that implements this interface. That's mandatory in Java. If you don't want to create a new class outside this class, you can create a new class inside the class or inside the method (which would be an anonymous class). Here's a sample:
public static void main(String []args){
Link b = new Link() {
#Override
public void mySampleMethod() {
System.out.println("hello");
}
};
b.mySampleMethod();
}
The purposes of using interfaces for programming instead of direct classes is already explained very well here: What does it mean to "program to an interface"? (no need to reinvent the wheel).

You can create a reference to an interface - you just cannot instantiate it. Let's say for example you have a interface A
public interface A {
public void someMethod();
}
Now you have another class that implements this interface
public class B implements A {
public void someMethod() { // do something }
public void someOtherMethod() { // do something else }
}
Now you can have something like
A a = new B();
While a reference type A it actually implements the method as defined in B. The object type is B. The reference type A indicates that it has only access to those methods in B that are specified by A and nothing else (in this case, it has access to someMethod() and not someOtherMethod()).

What exactly is b...
b contains a reference to an instance of a class that implements Link. The reference can, of course, be null.
and how could it ever have a practical purpose?
Its practical purpose is pretty much the same as any other Java reference.
Of course, the code as it is does not really put b to any use. However, it's not hard to imagine similar code that would (you'd need to have a class that implements Link, and create an instance of that class).

For instance interfaces are widely used in polymorphism. So if you have multiple classes implementing interface, you could keep them in the same way:
class One implements Link {..}
class Two implements Link {..}
public static void main(String[] arg) {
Vector<Link> links;
Link link1 = new One();
Link link2 = new Two();
links.add(link1);
links.add(link2);
for (Link l : links) {
l.mySampleMethod();
}
}

Related

Difference between pointing Interface and class ref to object?

Please read full question, Its different from this type of question
Difference between interface and class objects
Example: 1
Class implementing Interface
public interface a{
void foo();
}
public class b implements a{
#Override
void foo(){}
void bar(){}
}
Working behaviour
a asd=new b(); can call only foo()
b asf=new b(); can call both foo() and bar()
I hope upto here its clear.
Example 2:
Now there is one class CheckingPhase and IdentifyCheckingPhase
class IdentifyCheckingPhase {
private static a getPhase() {
return a;
}
private static void matchPhase(){
(CheckingPhase)IdentifyCheckingPhase.getPhase().bar();
}
}
class CheckingPhase implements a {
#Override
void foo() {
}
void bar(){
}
}
In Example 1. Interface instance only able to call its own implemented method in class and class instance able to all methods (class itself and Interface too). If that's a case, am sure something different being maintanied in compiler side that's why its able to differentiate.
Doubt First, Its correct to say that Interface and Class ref always points to different types instances of same class ? I guess yes, that's they are able to call their own methods. (Interface only its own methods but class ref can call all)
If not, Then In second example, a returned from getPhase(), should not be allowed to replace with CheckingPhase in matchPhase() and call its class instance method. Because a allowed to call only foo and CheckingPhase can call foo and bar both.
Doubt 2, I'm wondering, Is it syntactically correct using CheckingPhase instead of a while coming from method getPhase() to matchPhase() ?
I hope its clear what am trying to ask. Please let me know if may qyestion is not clear. (Its more about how java is using Syntax for above use case)

Clarification on collection's iterator [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

Why we can create an interface instance variable although Interface can't be instantiated?

I have following Interface declared
public interface MyInterface {
void do_it_now();
}
The I can do
public class MainClass{
public static void main(String[] args) {
MyInterface mainClass = new MyInterface() {
#Override
public void do_it_now() {
}
};
}
}
Now My Question regarding the above code is by definition Interface can't be instantiated
Whey we are allowed have a instance variable Type of Interface in java. What is the meaning of new MyInterface() line.
I want to know whats going on under the hood.
I have also gone through the post quite slimier to my question. but answer is not quite satisfactory to me .
Please don't give negative feedback or block my account if you found my question stupid post comment I will remove it.
Being able to have a variable of an interface type allows you to assign to that variable an instance of any class that implements that interface. Then you can use that variable to execute interface methods of that instance without caring about the specific implementation being used. It makes your code much more general, since you can switch to a different implementation of the interface without changing the code that uses the variable of the interface type.
You are making an "Anonymous Class" in the second code block. This means that it creates a class that implements the interface or class that you write. Its basically a short hand for making a subclass that implements the interface (MyInterface)
I want to know whats going on under the hood.
Consider the code below, assuming the interface MyInterface defined in your question.
Two inner classes are defined; the first class is anonymous (having no name) and the second class is named MyClass. Each of these two classes implements MyInterface.
// declare variable of type MyInterface
MyInterface myVariable;
// assign the variable to an instance of anonymous class that implements MyInterface
myVariable = new MyInterface() {
#Override
public void do_it_now() {
}
};
// define a named class that implements MyInterface
class MyClass implements MyInterface {
#Override
public void do_it_now() {
}
}
// assign the variable to an instance of named class that implements MyInterface
myVariable = new MyClass();
What's going on under the hood is, the java compiler compiles new MyInterface() {...}; into a separate class file with a name like $1.class, just like it compiles MyClass into a separate class file with a name like MyClass$1.class.

Changing a class variables type

I have two different interfaces which employ the same methods but dont implement or extend each other. These two interfaces are each extended by another class which implements the interfaces methods
I then have a class which is located in a seperate package which calls the interface methods.
So the class has methods which calls the methods of the interfaces, which are all the same.
public void doThis(){
connection.doThis();
}
public void doThat(){
connection.doThat();
}
public void doAnother(){
connection.doAnother();
}
Now, i want to make the variable connection work for both interface1 and interface2.
My idea was to set connection as a class variable
Object connection
and then to change it type to interface1 or interface2 depending on a condition:
if(this){
//condition which converts connection to type interface1
}
else{
//condition which converts connection to type interface2
}
How do i do this. Can i do this?
I have been given an interface which can not be changed, yet does not implement remote. But my project uses RMI. So i created a 2nd interface in a seperate package which implemets Remote. Thus the reason for 2 different interfaces that do he same thing.
I think it would be easier to make the class containing the method 'connection' public, as it would be accessible from all packages.
This seems like a really weird setup, but I won't question you.
If you know the condition at the method call site (eg, the condition is a constant flag passed to the method), you could parameterize the method with a generic instead. For example:
public class TestGenerics {
public static interface A {
public void a();
}
public static interface B {
public void a();
}
public static class C implements A, B {
public void a() {
System.out.println("a");
}
}
public static <T> T getCAsT() {
return (T) new C();
}
public static void main(String[] args) {
A a = TestGenerics.<A>getCAsT();
B b = TestGenerics.<B>getCAsT();
a.a();
b.a();
}
}
Otherwise, I would try to merge the two interfaces in some way.

Java - Basics of Class Instantiations and Access

This is a very basic question, but I'd quite like an explanation of why my question can or cannot be achieved.
If I have a class (A) which contains say a string, with a set method for that string. And I instantiate another class (B) from the first class (A), why can't I then access the first class (A) from the new class (B) to call the set method for the string in the first class (A).
The only reason I ask is that I'm working on a project with a similar problem, from a main class I create a new class which returns some buttons. And when a button is clicked the ActionListener in the main class is supposed to change the String in the initial class, but I cannot seem to access the set Method of the original class without re-instantiating the class.
Sorry if that sounds rambled, but I really want to understand why this is an issue, and what the correct way of doing it is. I know I'll probably be shot down on this, but any help is appreciated.
Because class B needs to hold a reference of the instance of A from which it has been created. There is no formal reason for which this should be made by default. For example:
public class B {
private final A creator;
public B(A creator) {
// you might want to check for non null A
this.creator = creator;
}
public void foo(String value) {
creator.setText(value);
}
}
Don't know if its the most elegant solution, but if you want object of class B to have a reference to object of class A (the creator) you can use Alessandro example code for class(B) and something like this in class A:
public class A
{
private String text;
public void createB()
{
new B(this);
}
public void setText(String b)
{
text = b;
}
}
Class cannot be called unless its been referenced by an Object. So you have to create something like this in Class B
myobject = FirstClass.new //I am not sure about java syntax as its been many years.
then you can call all the methods of FirstClass on this object and use them in SecondClass.
If B extends A, you can invoke the public methods in B that pertain to A.
If B doesn't extend A, it has no knowledge of A's methods. This is just how Java's inheritance works.

Categories