Can we create an object of an interface? - java

interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString() {
return "test";
}
});
}
}
What is the result?
A. test
B. null
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 1.
E. Compilation fails because of an error in line 4.
F. Compilation fails because of an error in line 5.
What is the answer of this question and why? I have one more query regarding this question. In line 4 we are creating an object of A. Is it possible to create an object of an interface?

What you are seeing here is an anonymous inner class:
Given the following interface:
interface Inter {
public String getString();
}
You can create something like an instance of it like so:
Inter instance = new Inter() {
#Override
public String getString() {
return "HI";
}
};
Now, you have an instance of the interface you defined. But, you should note that what you have actually done is defined a class that implements the interface and instantiated the class at the same time.

test should be the output. This is an example of an anonymous inner class.
This is a very common pattern used with the Comparator interface as an emulation of closures.

Try this too... The name of anonymous class is generated!
Inter instance = new Inter() {
public String getString() {
return "HI" + this.getClass();
}
};

The trick is not only about the anonymous inner class, this prints test cause it overrides the toString method and while System.out.println a Object it implicit call it's toString method.

We can create an object of an anonymous class, that implements the interface:
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.
If you have an interface, that declares one method toString, you can first create a class, that implements this inerface, and then create an object of this class:
interface TestA {
String toString();
}
class TestB implements TestA {
#Override
public String toString() {
return "test";
}
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestB());
}
}
Or you can create an object of an anonymous class to simplify this code:
interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
#Override
public String toString() {
return "test";
}
});
}
}
In both cases it prints "test".

I don't know the significance of this question. If this is an interview question, then I can say it's okay. But in real time it's not the right approach to implement an inheritance.So coming to the answer of the question, here what you are doing is an anonymous inner class .
Here you are instantiating a class and implementing the inheritance by writing,
System.out.println(new TestA() {
public String toString() {
return “test”;
}
});
and ofcourse the result would be test

Related

Java - inheritance, class with methods

I have my subclass:
public class Actions extends Main{
public void getFireTarget() {
GameObject target = getGameObjects().closest("Target");
do{
log("Shooting at the target");
getMouse().click(target);
} while(target != null && !getDialogues().inDialogue() && getLocalPlayer().getTile().equals(rangeTile));
}
}
I want to write similar methods, so I can call them in my Main class, so I don't have to write over and over.
My main class looks like this (won't fully paste it as it's long):
public class Main extends AbstractScript{
...code here
Actions actions = new Actions();
}
So I am trying to implement the methods in Actions by doing actions.getFireTarget(), which seems to work. But when I compile, I am getting two compile errors:
1) In the Main class, in the line: Actions actions = new Actions();
2) In the Actions class, in the line where I am extending the superclass.
Am I missing something in the sub class in order to store methods and then call them in the main method? Please advise! Thanks
The syntax is wrong. () are not allowed here: public class SomeName(). Remove the brackets.
I am having trouble understanding your details.
Here is a short info about inheritance:
public class A{
protected int t;
public void methodA(){}
}
public class B extends A{
#Override
public void methodA(){}
public void methodB(){}
}
If you override the methodA in class B, any call from a instance of class B to the method will use the method defined in class B. (If you dont write the method in class B, it will use the method from class A)
Objects of class A cannot use methodB() defined in class B.
Also you can access the field t in class B, because of the protected modified.
I think its better for you your problem to instantiate other class to your main class if you have same function name or same variable name. try to compile and run this code
public class First{
Second sec = new Second();
String s = "This is first";
public First(){
System.out.println(this.s);
System.out.println(getSecondString());
System.out.println(sec.getSecondString());
}
public String getSecondString(){
return "This is first";
}
public static void main(String args[]){
new First();
}
}
public class Second {
String s = "This is second";
public String getSecondString(){
return s;
}
}

Avoid Object Creation in Java

How to stop other classes to create the object of the class using new operator in java. For Example, i have one class A. i don't want any other class to create its object using new operator.
One Approach is that i can throw IllegalArgumentException in the constructor of class A.
is there any other?
public class A{
public A(){
throw IllegalArguementException();
}
}
The approach what you followed is wrong.. you can't create object of your class as well with this approach.
So you must make your construction private and write static method to get the instance of the class.
class Test
{
private Test(){ }
public static Test getTestInstance(){
return new Test();
}
}
Hope it helps,
You can do it by making the constructor private.
class A
{
int i;
private A()
{
i=1;
}
public static A getInstance()
{
return new A();
}
}
class B
{
A a;
public B()
{
/* a=new A(); //This doesn't compile */
}
}
Implementing Singleton in Java 5 or above version using Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment.
public enum SingletonEnum {
INSTANCE;
public void doYourStuff(){
System.out.println("Singleton using Enum");
}
}
And this can be called from clients :
public static void main(String[] args) {
SingletonEnum.INSTANCE.doYourStuff();
}
You can make the class abstract (though in this case no instance of this class can be instantiated by any class, so perhaps it's not what you want), or make the constructor private.
private A() {}
Make the constructor private.

A sorta extentsion on a method java

So i'm creating a API to java and i need a extention like thing on my method. Example:
someMethod().getName();
Something like that. Anyone know how?
What you are trying to do is something called method chaining. Let's put this example:
obj.methodOne().methodTwo()
This will call methodTwo() from the object returned by the call obj.methodOne(), so you can think the above chain as if it were this:
(obj.methodOne()).methodTwo()
Let's say you have this class:
public class MyClass2 {
public int methodTwo() {...}
}
Then, to be able to call methodTwo from the result of obj.methodOne(), the method methodOne() should return an instance of the class MyClass2:
public class MyClass1 {
public MyClass2 methodOne() {
return new MyClass2(); // returns instance of 'MyClass2'
}
}
Not sure what you mean, but this may help
class Foo {
Object someMethod() {
...
return new Object() {
public String toString() {
return "Bar";
}
}
}
}
What you're doing is returning an anonymous class and that overrides toString().
You can read more about anonymous classes here: http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
I think you are unable to express your question.
1) If you want to have toString() method in a class you can do the following:
public class XYZ
{
//Your properties and methods
#Override
public String toString()
{
//Manipulate what you want to return as a String
return a_string;
}
}
2) You want to call a method on the result of a method. Method Chaining
class XYZ
{
//Your properties and methods
public ABC getABC()
{
return an_ABC_object;
}
}
class ABC
{
public void doSomething()
{
// do some work or print something
}
}
public class Test
{
public static void main(String arg[])
{
XYZ xyz=new XYZ();
xyz.getABC().doSomething();
}
}

If interface cannot have a constructor, what happens here?

need some help on this, If interface cannot have a constructor, what happens here?
interface A{
String toString();
}
public class B{
public static void main(String[] args) {
System.out.println(new A() {
public String toString() {
return "what happens here!!";
}
});
}
}
An instance of an anonymous class implementing A is created.
This has very little to do with constructors, except that the default no-arg constructor will be called, and the toString() method is already defined in the Object class, so the interface is superfluous.
public static void main(String[] args) {
System.out.println(new A() {
public String toString() { return "what happens here!!"; }
});
}
can be more explicitly rewritten as follows:
public static void main(String[] args) {
class ImplA() extends Object implements A {
public ImplA() { super(); }
public String toString() { return "what happens here!!"; }
}
System.out.println(new ImplA());
}
From the above you can understand the following:
the local class ImplA is a subclass of Object and also implements A;
Object has a nullary constructor;
ImplA defines a nullary constructor, which delegates to Object's nullary constructor;
the constructor thus declared is called when writing new ImplA();
Your version of code just employs Java's syntactic sugar which lets you combine local class declaration with class instantiation into a single expression.

Super class which uses the values from children

I wanted to implement a method in a abstract class that is called by the inherited classes and uses their values.
For instance:
abstract class MyClass{
String value = "myClass";
void foo(){System.out.println(this.value);}
}
public class childClass{
String value="childClass";
void foo(){super.foo();}
}
public static void main(String[] args){
new childClass.foo();
}
This will output "myClass" but what I really want is to output "childClass". This is so I can implement a "general" method in a class that when extended by other classes it will use the values from those classes.
I could pass the values as function arguments but I wanted to know if it would be possible to implement the "architecture" I've described.
A super method called by the inherited class which uses the values from the caller not itself, this without passing the values by arguments.
You could do something like this:
abstract class MyClass {
protected String myValue() {
return "MyClass";
}
final void foo() {
System.out.println(myValue());
}
}
public class ChildClass extends MyClass {
#Override
protected String myValue() {
return "ChildClass";
}
}
and so on
This is a place where composition is better than inheritance
public class Doer{
private Doee doee;
public Doer(Doee doee){
this.doee = doee;
}
public void foo(){
System.out.println(doee.value);
}
}
public abstract class Doee{
public String value="myClass"
}
public ChildDoee extends Doee{
public String= "childClass"
}
...
//Excerpt from factory
new Doer(new ChildDoee);
I believe you are asking whether this is possible:
public class MyClass {
void foo() {
if (this instanceof childClass) // do stuff for childClass
else if (this intanceof anotherChildClass) // do stuff for that one
}
}
So the answer is "yes, it's doable", but very much advised against as it a) tries to reimplement polymorphism instead of using it and b) violates the separation between abstract and concrete classes.
You simply want value in MyClass to be different for an instance of childClass.
To do this, change the value in the childClass constructor:
public class childClass {
public childClass() {
value = "childClass";
}
}
Edited:
If you can't override/replace the constructor(s), add an instance block (which gets executed after the constructor, even an undeclared "default" constructor):
public class childClass {
{
value = "childClass";
}
}

Categories