How do I create an object of an abstract class and interface? I know we can't instantiate an object of an abstract class directly.
You can not instantiate an abstract class or an interface - you can instantiate one of their subclasses/implementers.
Examples of such a thing are typical in the use of Java Collections.
List<String> stringList = new ArrayList<String>();
You are using the interface type List<T> as the type, but the instance itself is an ArrayList<T>.
To create object of an abstract class just use new just like creating objects of other non abstract classes with just one small difference, as follows:
package com.my.test;
public abstract class MyAbstractClass {
private String name;
public MyAbstractClass(String name)
{
this.name = name;
}
public String getName(){
return this.name;
}
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyAbstractClass ABC = new MyAbstractClass("name") {
};
System.out.println(ABC.getName());
}
}
In the same way You can create an object of interface type, just as follows:
package com.my.test;
public interface MyInterface {
void doSome();
public abstract void go();
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyInterface myInterface = new MyInterface() {
#Override
public void go() {
System.out.println("Go ...");
}
#Override
public void doSome() {
System.out.println("Do ...");
}
};
myInterface.doSome();
myInterface.go();
}
}
There are two ways you can achieve this.
1) Either you extend / implement the Abstract class / interface in a new class, create the object of this new class and then use this object as per your need.
2) The Compiler allows you to create anonymous objects of the interfaces in your code.
For eg. ( new Runnable() { ... } );
Hope this helps.
Regards,
Mahendra Liya.
You can provide an implementation as an anonymous class:
new SomeInterface() {
public void foo(){
// an implementation of an interface method
}
};
Likewise, an anonymous class can extend a parent class instead of implementing an interface (but it can't do both).
public abstract class Foo { public abstract void foo(); }
public interface Bar { public void bar(); }
public class Winner extends Foo implements Bar {
#Override public void foo() { }
#Override public void bar() { }
}
new Winner(); // OK
"instantiate" means "create an object of".
So you can't create one directly.
The purpose of interfaces and abstract classes is to describe the behaviour of some concrete class that implements the interface or extends the abstract class.
A class that implements an interface can be used by other code that only knows about the interface, which helps you to separate responsibilities, and be clear about what you want from the object. (The calling code will only know that the object can do anything specified in the interface; it will not know about any other methods it has.)
If you are using someone else's code that expects a Fooable (where that is the name of some interface), you are not really being asked for an object of some Fooable class (because there isn't really such a class). You are only being asked for an instance of some class that implements Fooable, i.e. which declares that it can do all the things in that interface. In short, something that "can be Foo'd".
You write a class that derives from the abstract class or implements the interface, and then instantiate that.
What you know is correct. You cannot create an object of abstract class or interface since they are incomplete class (interface is not even considered as a class.)
What you can do is to implement a subclass of abstract class which, of course, must not be abstract. For interface, you must create a class which implement the interface and implement bodies of interface methods.
Here are orginal tutorial on oracle site, http://download.oracle.com/javase/tutorial/java/IandI/abstract.html and http://download.oracle.com/javase/tutorial/java/concepts/interface.html
You can not instantiate the abstract class or an interface, but you can instantiate one of their subclasses/implementers.
You can't instantiate an abstract class or an interface, you can only instantiate one of their derived classes.
In your example
MyAbstractClass ABC = new MyAbstractClass("name") {
};
You are instantiating any class that implements Suprising.
public abstract class AbstractClass { ... }
public interface InterfaceClass { ... }
// This is the concrete class that extends the abstract class above and
// implements the interface above. You will have to make sure that you implement
// any abstract methods from the AbstractClass and implement all method definitions
// from the InterfaceClass
public class Foo extends AbstractClass implements InterfaceClass { ... }
NO, we can't create object out of an interface or Abstract class because
Main intention of creating an object is to utilize the wrapped methods and data.
As interface don't have any concrete implementation hence we cannot.
For abstract class we may have concrete method or abstract method or both.
There is no way for the API developer to restrict the use of the method thats don't have implementation.
Hope help.
No, you are not creating the instance of your abstract class here. Rather you are creating an instance of an anonymous subclass of your abstract class. And then you are invoking the method on your abstract class reference pointing to subclass object.
Related
I am trying to understand how default methods deal with diamond problem in various scenarios. And, this is one of the scenario which I'm not able to understand.
Following is the description,
1. Interface with a default method method()
2. Abstract Class with a method method()
3. Concrete Class implementing the above interface and extending the abstract class.
interface Interface {
default void method() {
System.out.println("Interface method");
}
}
abstract class AbstractClass {
void method() {
System.out.println("Abstract class method");
}
}
// Concrete class definition first starts
public class ConcreteClass extends AbstractClass implements Interface {
#Override
public void method() {
super.method();
}
public static void main(String[] args) {
Interface test = new ConcreteClass();
test.method();
}
}
// Concrete class definition first ends
// Concrete class definition Second starts
public class ConcreteClass extends AbstractClass implements Interface {
public static void main(String[] args) {
Interface test = new ConcreteClass();
test.method();
}
}
// Concrete class definition Second ends
My queries,
1. Why does definition first always gives output as "Abstract class method" even when I use the Interface type for concrete class object?
2. Why definition second doesn't compile?
If compiler is using abstract class implementation in definition first, then it should be able to identify that it will always use Abstract class implementation in definition second.
This behavior is very confusing to me and any help is greatly appreciated.
Otherwise, the more I delve deeper into this, the more confusing it gets.
Edit 1 :
Compilation error in second definition is "The inherited method AbstractClass.method() cannot hide the public abstract method in Interface"
Default methods are just that: defaults. If there is an implementation, it will be used. If there isn't, the default will be used. There is no diamond problem here (there can be with multiple defaults, however).
1) Dynamic dispatch
2) The abstract class gives the method named method package-private access; the interface demands it be public.
I have question that is more or less technical. I would like to do the following:
Have a class that will define both a default constructor and another constructor that will create a new object called NamedRunnable.
This class will effectively implement the Runnable interface thus including the run method that it provides.
I want to find a way to no explicitly implement the run method within the the 'NamedRunnable' class itself but have it implemented within all member that will subclass the said class.
Is something like this possible?
If this is something you meant, then yes it is possible :)
public class NamedRunnable implements Runnable {
public NamedRunnable(String name) {
// ....
}
public void run() {
// ...,
}
}
It sounds like you want an abstract class (can't be instantiated) that implements Runnable:
abstract class NamedRunnable implements Runnable {
private String name;
protected NamedRunnable(String _name) {
this.name = _name;
}
}
Note that that doesn't implement run. run is implicitly abstract in that class, as though you had included
abstract public void run();
...because we declare the interface but don't implement it (which we wouldn't be allowed to do if the class weren't declared abtract).
You'd use that as a base class for a concrete class, e.g.:
class Thingy extends NamedRunnable {
public Thingy(String name) {
super(name);
}
#Override
public void run() {
// ...
}
}
The concrete class has the run implementation, and can be instantiated.
Given an interface:
public interface GoAlgorithm
{
public void go();
}
A class which implements the interface:
public class GoByFlyingFast implements GoAlgorithm
{
public void go()
{
System.out.println("Now I'm flying FAAAAST. Woo-hoo!");
}
}
An abstract class
public abstract class Vehicle
{
private GoAlgorithm goAlgorithm;
public Vehicle()
{
System.out.printf("A new vehicle has entered the race! \n");
}
public void setGoAlgorithm(GoAlgorithm algorithm)
{
this.goAlgorithm = algorithm;
}
public void go()
{
this.goAlgorithm.go();
}
}
A class extending the abstract class:
public class Tomcat extends Vehicle
{
public Tomcat()
{
setGoAlgorithm(new GoByFlyingFast());
}
}
(Code examples from Design Patterns for Dummies)
Is there a way, within the abstract class's implementation of the interface's method, to determine the subclass of the object invoking the method of the interface?
Can go() determine if a Tomcat object is invoking the go() method as defined by the Vehicle class?
Apologies if this question has already been posed. As evidenced by this question's title, I'm struggling to word my question concisely.
Thank you!
EDIT: Pure curiosity question
Theoretically yes. You can get the current stack trace with Thread.getStackTrace(), analyze it and look at the dynamic class of your caller. However, this would be VERY bad design.
Alternatively you can have your subclasses implement a getName() function, which returns their classname, so you could access that in your superclass.
In any case, it is good design if your (abstract) classes do not change their behavior based on which class is subclassing them. So there should not be a need for obtaining such information.
Wat does it mean by indirect Instantiation of abstract class ? how do
we achieve this ?
as i tried few times like .. it gives error has any one done something regarding this
abstract class hello //abstract class declaration
{
void leo() {}
}
abstract class test {} //2'nd abstract class
class dudu { //main class
public static void main(String args[])
{
hello d = new test() ; // tried here
}
}
We can't instantiate an abstract class .If we want than we have to extend it.
You can't instantiate an abstract class. The whole idea of Abstract class is to declare something which is common among subclasses and then extend it.
public abstract class Human {
// This class can't be instantiated, there can't be an object called Human
}
public Male extends Human {
// This class can be instantiated, getting common features through extension from Human class
}
public Female extends Human {
// This class can be instantiated, getting common features through extension from Human class
}
For more: http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
Wat does it mean my indirect instanciation of abstract class ? how do we achieve this ?
I'd need to see the context in which that phrase is used, but I expect that "indirect instantiation" means instantiation of a non-abstract class that extends your abstract class.
For example
public abstract class A {
private int a;
public A(int a) {
this.a = a;
}
...
}
public B extends A {
public B() {
super(42);
}
...
}
B b = new B(); // This is an indirect instantiation of A
// (sort of ....)
A a = new A(99); // This is a compilation error. You cannot
// instantiate an abstract class directly.
You can't create instance of abstract class, I think this is what you are trying to do.
abstract class hello //abstract class declaration
{
void leo() {}
}
class test extends hello
{
void leo() {} // Custom test's implementation of leo method
}
you cannot create object for Abstract class in java.
Refer this link-http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
I am having some interesting problem with interfaces, please help me understand this concept.
I have three interfaces Itest, Itest3, Itest4. Interface Itest extends both Itest3 and Itest4 interfaces.
They both interfaces have common one method public void one(); Now a class Test implements Itest interface and overrides method one()
Now of which interface it inherits method of? What if I want to inherit common method of specific interface.
And
What effect it has on polymorphism ? what if another class only inherits Itest3 only. I think this will break at runtime.
Please help me understand what the advantage is of that?
Code is here...
public interface ITest extends Itest4,Itest3 {
public static interface ITest2{
}
}
public interface Itest3 {
public void one();
}
public interface Itest4 {
public void one();
}
public class Test implements ITest {
#Override
public void one() {
//Which interface method it overrides?
}
public static void main(String... arg) {
new Test();
}
}
The answer is: it doesn't matter.
An interface is just declarations, not code. Both interfaces declare a method public void one(). When you have an implementing class which implements this method, it implements it for both interfaces at the same time. This implementation in class Test doesn't override anything. It's the first implementation. There are no implementations in the interfaces it could override - just two identical declarations for it.
When another class implements ITest3, it will need its own implementation for public void one(). Just like any other class which implements ITest4, or ITest. The only case where you wouldn't need an own implementation, is when you would have a class which extends the class Test, because it could inherit the implementation from Test.
The declaration
public interface Itest3 {
public void one();
}
Simply states that any implementer of Itest3 will provide a method that is named one, takes no arguments, and returns void.
In exactly the same way
The declaration
public interface Itest4 {
public void one();
}
also states that any implementer of Itest4 will provide a method that is named one, takes no arguments, and returns void.
Interfaces simply exist to specify a behavioral contract, irrespective of the implementation of said behavior.
Thus,
public class Test implements ITest {
#Override
public void one() {
//Defines the behavior of both interfaces
}
}
Defines a class which implements both interfaces.
This is because the method implementation satisfies the requirements of both interfaces.