interface Sporty {
public void beSporty();
}
class Ferrari implements Sporty {
public void beSporty() {
System.out.println("inside Ferrari impelemnting Sporty");
}
}
class RacingFlats implements Sporty {
public void beSporty() {
System.out.println("inside RacingFlats impelemnting Sporty");
}
}
public class TestSportythings {
public static void main(String[] args) {
Sporty[] sportyThings = new Sporty[3];
sportyThings[0] = new Ferrari();
sportyThings[1] = new RacingFlats();
}
}
You can call methods from Array instance of the interface by an object of a class which is implemented that method of the interface.
Like the following:
sportyThings[0].beSporty();
And you will get output:
inside Ferrari impelemnting Sporty
But if you call beSporty() by
sportyThings[2].beSporty();
You will get NullPointerException as sportyThings[2] is not initialized (by new).
Related
Is there any way by which I can cast a reference of type Object, assuming that the reference could point to any class I defined, to said defined class at runtime?
I've been trying to work it out and the code I came out with is:
public class SomeTestBench {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
myEntity a = new myEntity("Hello Code!");
Receptacle cage = new Receptacle();
cage.injectYourEntity(a);
((cage.itsClass) cage.theEntity).exertExistence();
}
}
That unfortunately does not work, as the class argument to that cast must be static.
Rest of the code:
public class myEntity extends Object{
String warcry;
myEntity(String warcry){
this.warcry = warcry;
}
public void exertExistence(){
System.out.println(this.warcry);
}
}
public class Receptacle {
Object theEntity;
Class itsClass;
public void injectYourEntity(Object it){
this.theEntity = it;
this.itsClass = it.getClass();
}
public void prodIt(){
System.out.println(theEntity.getClass());
}
}
Why don't you just do this using Generics.
public static void main(String[] args) {
myEntity a = new myEntity("Hello Code!");
Receptacle<myEntity> cage = new Receptacle<>();
cage.injectYourEntity(a);
cage.theEntity.exertExistence();
}
//
//That unfortunately does not work, as the class argument to that cast must be static.
//
//Rest of the code:
class myEntity {
String warcry;
myEntity(String warcry){
this.warcry = warcry;
}
public void exertExistence(){
System.out.println(this.warcry);
}
}
class Receptacle<T> {
T theEntity;
public void injectYourEntity(T it){
this.theEntity = it;
}
public void prodIt(){
System.out.println(theEntity.getClass());
}
}
To call a no-arg method named exertExistence() on an object of unknown type, you have three choices:
Use generics. See answer by WJS.
Use reflection:
Receptacle cage = new Receptacle();
cage.injectYourEntity(new myEntity("Hello Code!"));
Method method = cage.itsClass.getMethod("exertExistence", null);
method.invoke(cage.theEntity, null);
Use an interface (recommended):
Receptacle cage = new Receptacle();
cage.injectYourEntity(new myEntity("Hello Code!"));
cage.theEntity.exertExistence();
interface MyInterface {
void exertExistence();
}
class myEntity implements MyInterface {
String warcry;
myEntity(String warcry){
this.warcry = warcry;
}
#Override
public void exertExistence(){
System.out.println(this.warcry);
}
}
class Receptacle {
MyInterface theEntity;
public void injectYourEntity(MyInterface it){
this.theEntity = it;
}
}
I'm trying to write a factory class that takes in a class inherited from a specific abstract base class and calls a static method on that class to perform some logic and data manipulation before creating one or more instances of that class based on that manipulated data. So far, this is what I have:
public abstract class Foobar {
public static void sayHi() {}
}
public class Foo extends Foobar {
public static void sayHi() {
System.out.println("Hi from Foo!");
}
}
public class Bar extends Foobar {
public static void sayHi() {
System.out.println("Hi from Bar!");
}
}
public class PolymorphicFoobar {
public PolymorphicFoobar(Class<Foobar> cls) {
// Do some logic before creating an instance
cls.sayHi();
}
}
class Playground {
public static void main(String[ ] args) {
// Neither works
new PolymorphicFoobar(Foo.class);
new PolymorphicFoobar((Class<Foobar>)Bar.class);
}
}
You can do it with reflection and a capture-of wildcard; like
public PolymorphicFoobar(Class<? extends Foobar> cls) {
try {
Method sayHi = cls.getMethod("sayHi");
sayHi.invoke(cls);
} catch (Exception e) {
e.printStackTrace();
}
}
And then to invoke it, the syntax is very similar to what you had (you're missing new, but otherwise the first form is good). Like,
public static void main(String[] args) {
new PolymorphicFoobar(Foo.class);
new PolymorphicFoobar(Bar.class);
}
Outputs
Hi from Foo!
Hi from Bar!
I have this class:
public class MyThread {
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
System.out.print("Test from Anonymous Class!");
}
};
Thread newThread = new Thread(thread);
newThread.run();
}
}
When i run this program, i get Test from Anonymous Class!.
Now, i'm trying to simulate this behavior with another class like this:
interface MyInterface {
public void doTest();
}
class MyClass implements MyInterface {
public MyClass() {}
public MyClass(MyInterface myInterface) {}
public void doTest() {
System.out.println("Test from MyClass!");
}
}
public class Test {
public static void main(String[] args) {
MyClass myClass1 = new MyClass() {
public void doTest() {
System.out.println("Test from Anonymous Class!");
}
};
MyClass myClass2 = new MyClass(myClass1);
myClass2.doTest();
}
}
When i run this program, i get Test from MyClass!. Why is in the fist example printing out Test from Anonymous Class!? How can i get the same behavior with MyClass class?
Thanks in advance!
It seems you want to implement a delegation from a class that takes as parameter of the constructor an interface.
The Thread constructor uses the Runnable instance provided as parameter as target of the execution when you invoke Thread#start() while your custom class doesn't mimic this behavior. You indeed do nothing with the MyInterface parameter passed :
public MyClass(MyInterface myInterface) {}
To implement a delegation, you should add a MyInterface field in MyClass and value it in the constructor.
Then use it in doTest() method.
public MyClass(MyInterface myInterface) {}
private MyInterface myInterface;
...
public MyClass(MyInterface myInterface) {
this.myInterface = myInterface;
}
public void doTest() {
// do some processing
..
// then delegate
myInterface.doTest();
}
}
That's because you're doing Nothing with your param myClass1
public MyClass(MyInterface myInterface) {}
You get the parameter, so what? if you want to do what the parameter do, you must invoke the method:
myClass1.doTest()
>"Test from Anonymous Class!"
What you're doing is rare, but if you invoke the method from the correct object, you will get what you want :)
Another way, rare but valid, is to have an instance variable, and call it:
class MyClass implements MyInterface {
MyClass myOtherClass;
public MyClass() {}
public MyClass(MyInterface myInterface) {
this.myOtherClass = myInterface;
}
public void doTest() {
System.out.println("Test from MyClass!");
}
}
Then, you call the method inside it:
public class Test {
public static void main(String[] args) {
MyClass myClass1 = new MyClass() {
public void doTest() {
System.out.println("Test from Anonymous Class!");
}
};
MyClass myClass2 = new MyClass(myClass1);
myClass2.myOtherClass.doTest(); // calling method from myClass1
}
}
You need to initialize your target ,so it will call the method in your class
class MyClass implements MyInterface {
MyInterface myInterface;
public MyClass() {}
public MyClass(MyInterface myInterface) {
this.myInterface=myInterface;
}
public void doTest() {
if(myInterface !=null){
myInterface.doTest();
return;
}
System.out.println("Test from MyClass!");
}
}
The answer is simple.
The run() method in Thread is overriden and it will always be the one to run.
In the second example myClass2 uses it instance doTest() method and myClass1 is never used, except in constuctor.
interface Y {
void search(String name);
}
class A implements Y {
void search(String name) {
//Is it possible to say: "If I was called from class B then do a search("B");
}
}
class B extends A {
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.search();
}
}
Given the above code is it possible to reason in superclass which subclass was used for calling a method?
The reason I want to do this is because the code in Search is very similar for all Subclasses, the only thing that changes is the Classname, so I thought there is no need to Override in each subclass. I have updated the code to reflect this. Please let me know if there is a better way of doing it/
Calling this.getClass() inside your search method will give you the concrete class of the current instance.
For example:
class Example
{
static class A {
public void search() {
System.out.println(getClass());
}
}
static class B extends A {}
public static void main (String[] args) throws java.lang.Exception
{
new A().search();
new B().search();
}
}
outputs
class Example$A
class Example$B
The cleanest way to do it is to override the method in each subclass.
interface Y {
void search();
}
class A implements Y {
public void search(){
search("A");
}
protected void search(String name) {
// implement your searching algoithm here
}
}
class B extends A {
public void search(){
search("B");
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.search();
}
}
That's the way inheritance is suppose to works. A super class should not know its subclasses.
And, in case you extends your class B, you can easily either:
-Keep the same behaviour as B:
class C extends B {
// do nothing, when calling search, it calls the method implemented in B
}
-Change the behaviour to search for "C"
class C extends B {
public void search(){
search("C"); // or search("whateveryouwant")
}
}
You can simply override the method in class B.
The other way could be to write the search() method as
void search() {
if (this.getClass().equals(B.class)) {
//The logic for B
} else if (this.getClass().equals(A.class)) {
//The logic for A
}
}
You have to provide the fully qualified name for the class.
Better follow template pattern.
interface Y {
void search(String name);
}
abstract class AbstractionTemplate implements Y{
#Override
public void search(String name) {
//a lot of code.
System.out.println("common stuff start");
doImplspecificStuffOnly();
System.out.println("common stuff end");
//a lot of code.
}
abstract void doImplspecificStuffOnly();
}
class A extends AbstractionTemplate{
#Override
void doImplspecificStuffOnly() {
System.out.println("a's stuff");
}
}
class B extends A {
#Override
void doImplspecificStuffOnly() {
System.out.println("B's stuff");
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.search("hey");
}
}
wondering how it is possible to call public m method?
public class Test1 {
public static void main(String[] args) {
Test1 test = new Test1() {
public void m() {
System.out.println("m");
}
};
}
}
I don't believe you can. You'd have to create an interface or subclass. (Well, okay, that's probably not true. You could probably do it with reflection.)
E.g., like this (where you call it via test.m() after construction):
public class Test1 {
public static void main(String[] args) {
SubTest1 test = new SubTest1() {
public void m() {
System.out.println("m");
}
};
test.m();
}
private static abstract class SubTest1 extends Test1 {
public abstract void m();
}
}
Or like this, where it happens during construction:
public class Test1 {
public static void main(String[] args) {
SubTest1 test = new SubTest1() {
public void m() {
System.out.println("m");
}
};
}
private static abstract class SubTest1 extends Test1 {
public SubTest1() {
this.m();
}
public abstract void m();
}
}
You can't define an anonymous class constructor, so that last uses the constructor of the SubTest1 class and the abstract method.
You cannot directly invoke m since test is of type Test1 which does not contain a method called m, but you should never find yourself in a situation like this. The whole point of anonymous classes is to alter some already-existent aspect of the base class's functionality, so adding new methods makes no sense. Consider rethinking your design or using a named class instead.
Of course, if you won't care about test in the future you could do this:
new Test1() {
public void m() {
System.out.println("m");
}
}.m();
Although you would rarely want to do something like this, it could be useful if you're working with Thread or Runnable and need to invoke the run method.
If Test1 had a method called "m" you could just call test.m() after you instantiated the inner class:
public class Test1 {
public static void main(String[] args) {
Test1 test = new Test1() {
public void m() {
System.out.println("New Behavior");
}
};
test.m();
}
public void m() {
System.out.println ("Default Behavior");
}
}
Running this would output:
New Behavior