Suppose I have an interface called Interface, and a concrete class called Base, which, to make thing a bit more complicated, has a ctor that requires some arguments.
I'd like to create an anonymous class that would extend Base and implement Interface.
Something like
Interface get()
{
return new Base (1, "one") implements Interace() {};
}
That looks reasonable to me, but it doesn't work!
(P.S: Actually, the Interface and Base are also generic classes :D. But I'll ignore that for now)
No, you can't do that with an anonymous class. You can create a named class within a method if you really want to though:
class Base {
}
interface Interface {
}
public class Test {
public static void main(String[] args) {
class Foo extends Base implements Interface {
};
Foo x = new Foo();
}
}
Personally I'd usually pull this out into a static nested class myself, but it's your choice...
This scenario makes little sense to me. Here's why: assume class Base is this:
class Base {
public void foo();
}
and Interface is this:
interface Interface {
public void bar();
}
Now you want to create an anonymous class that would be like this:
class MyClass extends Base implements Interface {
}
this would mean that MyClass inherits (or possibly overrides) method bar from Base and must implement method foo from Interface. So far so good, your class has these two methods either way.
Now, think what happens when you are returning an object of type Interface from your method: you only get the functionality that Interface offers, namely method foo. bar is lost (inaccessible). This brings us down to two cases:
Extending Base is useless because you do not get to use its methods, since the new object is seen as an Interface.
Interface also has a method foo, but that would mean that Base itself should implement Interface, so you can just extend Base directly:
class Base implements Interface {
public void foo();
public void bar();
}
class MyClass extends Base {
}
Related
I'm newbie to Java. I would like to ask different between the following interface examples?
public interface MyInterface {
public void doSomething();
}
like this
public class MyClass implements MyInterface {
public void doSomething {....}
}
and this
public class MyClass implements MyInterface {
protected MyInterface myInterface;
public MyClass (MyInterface myInterface) {
this.myInterface = myInterface;
}
public void doSomething () {
myInterface.doSomething();
}
}
In first case you implement an interface using a class and you implement the function doSomething in that class. you can call the doSomething function by creating an instance of the class MyClass
MyInterface obj = new MyClass();
obj.doSomething();
In second case, you wont be even able to instantiate an instance of the MyClass because it needs another instance of it-self or another class which implements that interface.
public class MyClass implements MyInterface {
public void doSomething {....}
}
MyClass implements the interface MyInterface. It means your class holds a concrete behavior that your interface promise. By implementing the interface your class guaranteed the MyClass has the concrete feature your interface abstracted in its declaration.
But I doubt you may not have a real scenario to implement an interface as well as create an instance of interface in a class. Second part of your question is one of the most famous design topic of inheritance vs composition. Chances of using both inheritance and composition together of an interface is barely rare.
The first two code are one interface and another class which implements the interface.
The third code is MyClass that implements MyInterface and creates a object reference to MyInterface named myInterface. The next part
public MyClass (MyInterface myInterface) {
this.myInterface = myInterface;
}
is a simple constructor and the next part
public void doSomething () {
myInterface.doSomething();
}
is calling of a method.
The first one is inheritance and the second one is composition. Inheritance is an "is-a" relationship, while composition is a "has-a".
For example, if there is a Pressable interface which represents everything that can be pressed, Button, Checkbox should implement it. If there is a Color class, the Button should have a composition relationship between the Color, since a Button should have a color, but a Button is not a type of Color.
A commonly known mistake is the java.util.Stack. Since a Stack is not a java.util.Vector, Stack should not inherit Vector.
An interface is an abstract type in Java and it specify a set of abstract methods that classes must implement. A class usually implement the interface as shown in your first example.
In your second example, even though MyClass is implementing the interface, the behaviour of doSomething method will depend on the instance of MyInterface implementation that it will get when instantiate MyClass object.
It is not possible to instantiate an interface. You will have to do something like below. Here MySecondClass implements the MyInterface.
MyClass m = new MyClass(new MyInterface()
{
#Override
public void doSomething()
{
// TODO Auto-generated method stub
}
});
MyClass m2 = new MyClass(new MySecondClass());
}
Let's say that I have an interface, and all classes that implement that interface also extend a certain super class.
public class SuperClass {
public void someMethod() {...}
}
public interface MyInterface {
void someOtherMethod();
}
//many (but not all) sub classes do this
public class SubClass extends SuperClass implements MyInterface {
#Override
public void someOtherMethod() {...}
}
Then if I'm dealing with an object of type MyInterface and I don't know the specific sub class, I have to hold two references to the same object:
MyInterface someObject = ...;
SuperClass someObjectCopy = (SuperClass) someObject; //will never throw ClassCastException
someObjectCopy.someMethod();
someObject.someOtherMethod();
I tried making the interface extend the super class, but it's a compiler error:
public interface MyInterface extends SuperClass {} //compiler error
I also thought of combining the interface and the super class into an abstract class like so:
public abstract class NewSuperClass {
public void someMethod();
public abstract void someOtherMethod();
}
But then i can't have a sub class that doesn't want to implement someOtherMethod().
So is there a way to signify that every class that implements an interface also extends a certain class, or do I have no choice but to carry around two references to the same object?
I think that the only solution you have would be to have a reference to both, but this indicates that you have a design flaw somewhere. The reason I say is because you should think of an interface as something that your implementing classes will always need. For example, a Car and Airplane both need a Drive() interface. A design reconsideration is probably worth your time. However, if you still want to follow that path, you can do the following:
public class ClassA {
public void methodA(){};
}
public abstract class ClassB extends Class A{
public void methodB();
}
After you have the above setup, you can now reference an object that has the two methods by doing the following:
ClassB classB = new ClassB();
classB.methodA();
classB.methodB();
Now you don't actually have to actually use two pointers to the same object.
I am just confused about abstract class concept. Please clear my doubt. Definition of Abstract class says we can not create object of such class, then what we called like A a = new A() { }. Example is below:
public abstract class AbstractTest {
public abstract void onClick();
public void testClick() {
}
}
public class A {
AbstractTest test = new AbstractTest() {
#Override
public void onClick() {
}
};
}
Then test is a object or what?
test is an object of an anonymous concrete sub-class of AbstractTest (note that it implements all the abstract methods of AbstractTest), which is why this sub-class can be instantiated.
On the other hand,
AbstractTest test = new AbstractTest();
wouldn't pass compilation, since that would be an attempt to instantiate an abstract class.
You are mixing up object and reference.
AbstractTest test = new AbstractTest() {
#Override
public void onClick() {
}
};
test here is a reference to a anonymous class that extends AbstractTest, the above code is like saying:
class MyClass extends AbstractTest {
#Override
public void onClick() {
}
}
AbstractTest test = new MyClass(); // test is a reference to a MyClass object
Abstract Class in my opinion needs to be explained together with Interface.
Interface allows you to specify operations that are supported/allowed on objects with that interface. More specifically Objects are instances of a Class which implements that Interface. Defining an interface allows you to describe a group of different classes of objects so that other objects can interact with them in the same manner.
Abstract Class is one step between interface and a Class (loosely speaking). Abstract Class allows you to specify operations that are supported by classes that extend it, but it also allows you to implement (some of) those operations. This way you can implement common methods for a group of classes in that abstract class. Other methods in the abstract class that are not implemented (aka abstract methods) need to be implemented by the class that extends it. The fact that you didn't implement all methods on an Abstract class naturally means you can't instantiate it (create an object of such class). There are other useful implementations for Abstract classes (i.e. callbacks).
In your example what you see there is that you are not really trying to just create an object that Abstract class you are also providing implementation of abstract method onClick();
That is the only way you can "create an instance of the abstract class" - technically speaking you are creating an instance of an Anonymous class (that is extending your abstract class) for which you provide implementation of inherited abstract methods.
can anybody tell me that. how can I call abstract class method to my own class in java?
thanks in advance
First of all look at you abstract class, it shall contain abstract methods and real methods. In the following sample the Foo class has an abstract method (FooMethod) and a real method (Yeee).
public abstract class Foo {
public abstract int FooMethod(int i);
public int Yeeee() {
for (int i = 0; i < 3; i++) {
int res = FooMethod(i);
// Do whatever
}
}
}
Abstract class are not meant to be directly used, so we have to inherit from them with a concrete class. The following inherits from the abstract (implementing the abstract method)
public class Bar extends Foo {
public int FooMethod(int i) {
// do something with i
}
public static void main (string [] args) {
Bar obj = new Bar();
obj.Yeeee();
}
}
Note: when in the main you call obj.Yeee() the base class method gets invoked, but in place of the abstract FooMethod, your own new implementation is used.
This is just the tip of the iceberg with abstract classes, but roughly should point you to the right direction.
Please take a good read here is a good tutorial and should give you some initial wisdom about inheritance and abstract classes.
You need to first create a subclass of the abstract class. This will then contain the methods of that abstract class. You use the "extends" keyword.
For example:
public class MyClass extends AbstractClass
{
//class content here...
}
For methods in abstract classes you need not to create the instance of the abstract class
So after importing the package in which the abstract class is present you can just call the method as below
YourAbstractClassName.methodName(args if any);
since abstract classes cant be instanciated in Java, You cant have member functions in this class and if you want to have one than their is a logical problem. However if you want to call the static methods, you can simply call them using class name, i.e.
YourClassName.fuctionName(parameters if any);
Do you mean how to implement that method in your class ?
if that is what you want to understand
then you just have to extend your class with the abstract one
for example
abstract class GraphicObject {....}
class Circle extends GraphicObject { ... }
try http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You can call the method in abstract class by creating an
object of subclasss of the abstract class
or
if u want to call from the abstract class then you have to make your method static then you can call from main method like
Abstract_className.methodName()
I was wondering if the next thing is possible for implementation:
Lets say I've got 2 interfaces while each one of them has 1 function header.
For example, iterface1 has function g(...) and interface2 has function f(...)
Now, I make a class and declaring that this class is implementing these 2 interfaces.
In the class I try doing the next thing:
I start implementing function g(...) and in it's implementation I make a local class that implements interface2 and I add to this class the implementation of f(...).
I'm not quite sure what you mean. I am picturing something like this:
interface Interface1
{
public void g();
}
interface Interface2
{
public void f();
}
class MyClass implements Interface1, Interface2
{
#Override
public void g()
{
class InnerClass implements Interface2
{
#Override
public void f()
{
}
}
}
}
Is that what you meant?
In this case, the answer is no. The inner class (InnerClass) works fine, but it doesn't count as an implementation of f for the outer class. You would still need to implement f in MyClass:
MyClass.java:11: MyClass is not abstract and does not override abstract method
f() in Interface2
Yes it is legal. However a class does not implement an interface because an inner class implements it. The class must implement the interface explicitly or declare itself as abstract.
Yes, it's legal. In the example you've given, your class should implement all methods of both interfaces, and your local class should implement all methods of interface2.