when should we declare a CLASS inside an INTERFACE in java? - java

Can Someone tell me with an example why an class should be defined inside an interface.
The below is the simple code i was trying.
interface Watsapp
{
class A
{
public void Validate()
{
}
};
abstract public void SendText();
public void SendPic();
};

its totally depends on logic requirements.
whenever we declare inner class, it treats as a data member so here also you can treat this class as a data member
just assume scenario some one needs object of A inside Interface and there is no class right now.
see eg.
public interface Watsapp
{
class A
{
public void Validate()
{
}
public String iDoSomething()
{
return "i did";
}
};
public A objOfA = new A();
abstract public void SendText();
public void SendPic();
};
And main Class is bellow:
public class TestMain {
public static void main(String[] str){
System.out.println( Watsapp.objOfA.iDoSomething());
}
}
mostly people create anonymous class for one time use, but here You created a class with name.
see:
public interface Watsapp
{
/*class A
{
public void Validate()
{
}
public String iDoSomething()
{
return "i did";
}
};*/
Thread t = new Thread()
{
public void run() {
// something ...
}
};
abstract public void SendText();
public void SendPic();
};
Thank you.

Related

In Java is it possible to check at runtime on which subclass a method was called?

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");
}
}

How to write an abstract main class

I need to write some importers. They need all the same initialization. So I try to write an abstract class, which does all the initialization and also has the main method, so that all sub-classes just need to implement run() to do their specific import work:
public abstract class AbstractImporter {
public AbstractImporter() {
// Initialization
}
public abstract void run();
public static void main(String[] args) {
AbstractImporter importer = new AbstractImporter();
importer.run();
}
}
public class ConcreteClass() {
public void run() {
// Do some importing
}
}
Of course it fails to create an instance of this abstract class (new AbstractImporter()).
Does anybody has any idea how to solve that? TIA!
Obviously you need a concrete class - anonymous or otherwise.
Better to move the main method to another class and instantiate the appropriate concrete class based on data (either your domain specific or a constant) and then run it. This way each implementation can be independent of other implementations.
public abstract class AbstractImporter {
public AbstractImporter() {
// Initialization
}
public abstract void run();
}
public class ConcreteImporter1 extends AbstractImporter {
public void run() {
//do something
}
}
public class ImporterMain() {
public static void main(String[] args) {
AbstractImporter importer = createImporter(args[1]);
importer.run();
}
private static AbstractImporter createImporter(String type) {
if (type.equals("1")) {
return new ConcreteImporter1();
}
....
}
}
new AbstracterImporter() {
public void run() {
// ...
}
};
I apologize for current lack of formatting, currently on a mobile device.
public abstract class AbstractImporter {
public AbstractImporter() {
// Initialization
}
public abstract void run();
public static void main(String[] args) {
AbstractImporter importer = new AbstractImporter(){
public void run() {
System.out.println("Anonymous implementation");
}
};
importer.run();
}
}
You cannot create an instance of an abstract class.
public abstract class AbstractImporter {
public AbstractImporter() {
// Initialization
}
public abstract void run();
}
public class ConcreteClass extends AbstractImporter{
public void run(){
//Implementation
}
public static void main(String args[]){
AbstractImporter ai = new ConcreteClass();
ai.run();
}
}

Java Co-Variance

For a project I want to provide a generic interface to resemble a workflow, like
public interface IWorkflow
{
public void start();
public void doWork();
public void end();
}
For that, I have lots of implementation, like
public class CoffeeWorkflow implements IWorkflow
{
public void start()
{
// setup coffee
// prepare dishes
// ...
}
public void doWork()
{
// drink coffee
}
public void end()
{
// wash dishes
}
}
Now I want to provide more information to those functions, like
public interface IWorkflowStartArgs
{}
And especially:
public class CoffeeWorkflowStartArgs implements IWorkflowArgs
To give it into the method
public interface IWorkflow
{
public void start(IWorkflowStartArgs args);
public void doWork();
public void end();
}
respectivly:
public class CoffeeWorkflow implements IWorkflow
{
public void start(CoffeeWorkflowStartArgs args)
{
}
}
But this does not work, as it is not recognized as implementation
of the interface.
Should I pass in an IWorkflowStartArgs and cast it inside?
Is there a better solution to that?
You can define interface like
interface IWorkflow<T extends IWorkflowStartArgs>
{
public void start(T args);
public void doWork();
public void end();
}
and when you create CoffeeWorkflow you can create something like
class CoffeeWorkflow implements IWorkflow<CoffeeWorkflowStartArgs>
{
#Override
public void start(CoffeeWorkflowStartArgs args) {
// TODO Auto-generated method stub
}
#Override
public void doWork() {
// TODO Auto-generated method stub
}
#Override
public void end() {
// TODO Auto-generated method stub
}
}
Java won't consider it as the specific implementation type.
Consider the following case, where you can see where the problem will occur (IF automatic mapping of implemented class in the function argument is seen valid by Java):
public class CoffeeWorkflow implements IWorkflow
{
public void start(IWorkflowStartArgs args)
{
// This is what Java sees as actual implementation
}
public void start(CoffeeWorkflowStartArgs args)
{
// This is yet again SEPARATE method with different signature
// In case of auto-casting (if there would have been), this method would be AMBIGUOUS
}
}
The solution?
Well use Generics as illustrated by #sanbhat
Or if you don't want to go into Generics,
Then I think you should pass in an IWorkflowStartArgs and cast it inside as you said first,
like this way:
public class CoffeeWorkflow implements IWorkflow
{
public void start(IWorkflowStartArgs args)
{
if (args instanceof CoffeeWorkflowStartArgs) {
CoffeeWorkflowStartArgs coffeeArgs = (CoffeeWorkflowStartArgs) args;
// ....
}
}
// ....
}
Suppose you have another similar class TeaWorkFlow,
then again you need to check instanceof.
This is why Generics were mainly introduced - To avoid repeatedly checking by instanceof;
And to serve as a general model for similar pattern classes.
There is a solution using a single generic parameter, that ensures type safety. Lets use the generic parameter WorkflowType for it:
interface IWorkflow<T extends WorkflowType>
{
public void start(IWorkflowStartArgs<T> args);
public void doWork(IWorkflowWorkArgs<T> args);
public void end(IWorkflowEndArgs<T> args);
}
You can now instantiate your generic parameter:
public class CoffeeWorkflowType extends WorkflowType {
}
Your CoffeeWorkflow looks like this:
public class Coffee implements IWorkflow<CoffeeWorkflowType> {
{
public void start(IWorkflowStartArgs<CoffeeWorkflowType> args);
public void doWork(IWorkflowWorkArgs<CoffeeWorkflowType> args);
public void end(IWorkflowEndArgs<CoffeeWorkflowType> args);
}
and the implementations for your workflow arguments:
public class CoffeeWorkflowStartArgs implements IWorkflowStartArgs<CoffeeWorkflowType> { ... }
public class CoffeeWorkflowWorkArgs implements IWorkflowWorkArgs<CoffeeWorkflowType> { ... }
public class CoffeeWorkflowEndArgs implements IWorkflowEndArgs<CoffeeWorkflowType> { ... }

Call different methods from different classes in a single reference in java

Having issue in Java,
we can call class methods like
interface samp{
public void printMsg();
}
ClassA implements samp{
public void printMsg()
{
S.o.p("Hi ClassA");
}
}
ClassB implements samp{
public void printMsg()
{
S.o.p("Hi ClassB");
}
}
public MainClass{
public static void main(String args())
{
samp s= new ClassA();
s.printMsg();
samp s= new ClassB();
s.printMsg();
}
}
we can do this, am having different type of class method not similar methods for all classes but I want to implement the future is it possible to do? is any other pattern for this, pls help me to find this.
like
ClassA{
public void fun1(){..}
public void fun2(){..}
}
ClassB{
public void fun3(){..}
public void fun4(){..}
}
want to call these methods using a single refrence, need to asign object to that refrence dynamically is it possible friends?...
Thanks in advance
You cant do that using common interface.You can only call the method which is defined in interface using an interface reference type, even though the object it points to belong to another class have different other methods.
you can call only those class function which are defined in interface because its reference can access only those functions. ex:
interface samp{
public void printMsg();
}
ClassA implements samp{
public void printMsg()
{
S.o.p("Hi ClassA");
}
public void newmthd(){
S.o.p("you can't call me from samp reference.");
}
}
ClassB implements samp{
public void printMsg()
{
S.o.p("Hi ClassB");
}
}
public MainClass{
public static void main(String args())
{
samp s= new ClassA();
s.printMsg();
s.newmthd() //error... s don't have any knowledge of this function.
samp s= new ClassB();
s.printMsg();
}
}
Define all the methods you want your reference to have in an a superclass, but leave the implementations empty. Then, create your subclass and override the necessary methods.
Example:
Class MySuperClass {
public void fun1() {}
public void fun2() {}
public void fun3() {}
public void fun4() {}
}
Class ClassA extends MySuperClass {
public void fun1() { //implementation details }
public void fun2() { //implementation details }
}
Class ClassB extends MySuperClass {
public void fun3() { //implementation details }
public void fun4() { //implementation details }
}
public Class Tester {
public static void main(String[] args) {
MySuperClass class1 = new ClassA();
MySuperClass class2 = new ClassB();
}
}

How can I get the benefits of implementation inheritance without tying my class to a particular implementation?

I'm developing an application which builds on a class written by another developer (for which I do not have the source).
I wish to use all of the functionality of said class but also to extend it with additional functionality. Ordinarily to achieve this I would have defined an interface (MyInterface) and have extended the external class (TheirClass) from my own (MyClass) while implementing MyInterface.
public interface TheirClassInterface {
public void theirMethod1();
public void theirMethod2();
}
public class TheirClass implements TheirClassInterface {
public void theirMethod1() { ... }
public void theirMethod2() { ... }
}
public class TheirOtherClass {
public void theirOtherMethod1(TheirClassInterface o) { ... }
}
public interface MyInterface() {
public void myMethod1();
}
public class MyClass extends TheirClass implements MyInterface {
public void myMethod1() { ... }
}
public class MyNewClass extends MyClass {
public void MyNewClassMethod() { ... }
}
The problem is complicated by the fact that:
I now wish to create a new class (MyNewClass) which adds additional functionality to MyClass but I don't want my code to be dependent on TheirClass.
I wish to be able to use my class as a parameter to the method of TheirOtherClass.
To combat this I refactored my code to instead use composition over inheritance and implementing TheirClassInterface. This works but requires me to implement many methods and delegate them to theirClassObject (in reality TheirClassInterface contains a very large number of methods).
public interface TheirClassInterface {
public void theirMethod1();
public void theirMethod2();
}
public class TheirClass implements TheirClassInterface {
public void theirMethod1() { ... }
public void theirMethod2() { ... }
}
public class TheirOtherClass {
public void theirOtherMethod1(TheirClassInterface o) { ... }
}
public interface MyInterface() {
public void myMethod1();
}
public class MyClass implements TheirClassInterface, MyInterface {
private TheirClass theirClassObject;
public void myMethod1() { ... }
public void theirMethod1() { theirClassObject.theirMethod1(); }
public void theirMethod2() { theirClassObject.theirMethod2(); }
}
public class MyNewClass extends MyClass {
public void MyNewClassMethod() { ... }
}
My question is whether my approach is appropriate in this case and whether it could be improved upon as it seems to me that my code uses an excessive amount of delegation to get the job done.
Many thanks for any guidance anyone can give on this.
Danny
First, as java is a strongly-typed single inheritance language, you cannot escape the delegation.
But you can avoid having to write a lot of delegation CODE, by using a dirty little trick with Proxies and reflection.
Code follows
public interface Interface1 {
void m1();
}
public interface Interface2 {
void m2();
}
public class Class1 implements Interface1 {
public void m1() {
System.out.println(1);
}
}
public class Class2 implements Interface2 {
public void m2() {
System.out.println(2);
}
}
public interface MixinInterface extends Interface1, Interface2 {
}
And this is how the magic happens
package j.with.pseudo.multiple.inheritance;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MixinBuilder {
public static Object buildMixed(Class _interface, Object... impls){
InvocationHandler h = new MixinHandler(_interface.getInterfaces(), impls);
return Proxy.newProxyInstance(MixinBuilder.class.getClassLoader(),
new Class[]{_interface}, h);
}
public static void main(String[] args) {
Class1 o1 = new Class1();
Class2 o2 = new Class2();
MixinInterface almost_like_multiple_inheritance_guy =
(MixinInterface) buildMixed(MixinInterface.class, o1, o2);
almost_like_multiple_inheritance_guy.m1();
almost_like_multiple_inheritance_guy.m2();
}
private static class MixinHandler implements InvocationHandler{
private Class[] interfaces;
private Object[] impls;
public MixinHandler(Class[] interfaces, Object[] impls) {
this.interfaces = interfaces;
this.impls = impls;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
int i=0;
for(Class _interface : interfaces){
if(method.getDeclaringClass().isAssignableFrom(_interface)){
return method.invoke(impls[i], args);
}
i++;
}
// TODO Auto-generated method stub
throw new RuntimeException("Method not found: "+method);
}
}
}
Pretty cool huh? :-)
You can't not-depend on a class if you're extending it; it's like having a definition of Human, which does not depend on the definition of Mammal, your optinos are to rewrite everything in the parent, or depend on it.
Many thanks for the answers so far. I've come up with a solution which I think seems reasonable and allows me to fully encapsulate the foreign class.
At the moment I've returned to the method discussed in the first block of code (repeated and extended below) and am now implementing my MyInterface interface for MyNewClass and delegating all interface operations to a composed object. The object to delegate to is decided at runtime by calling a static method on a Factory.
public interface TheirClassInterface {
public void theirMethod1();
public void theirMethod2();
}
public class TheirClass implements TheirClassInterface {
public void theirMethod1() { ... }
public void theirMethod2() { ... }
}
public class TheirOtherClass {
public void theirOtherMethod1(TheirClassInterface o) { ... }
}
public interface MyInterface() {
public void myMethod1();
}
public class MyClass extends TheirClass implements MyInterface {
public void myMethod1() { ... }
}
public class MyNewClass implements MyInterface {
private MyInterface myObject;
public MyNewClass() {
myObject = MyClassFactory.createMyClass();
}
public void myMethod1() {
myObject.myMethod();
}
public void MyNewClassMethod() { ... }
}
Once again, thanks for the ideas. I'm now going to look into them all and see if I can use them to improve my code.
Cheers,
Danny

Categories