This question already has answers here:
Can we instantiate an abstract class?
(16 answers)
Closed 9 years ago.
Couldy you clarify why this works:
public abstract class AbstractClassCreationTest {
public void hello(){
System.out.println("I'm the abstract class' instance!");
}
public static void main(String[] args) {
AbstractClassCreationTest acct = new AbstractClassCreationTest(){};
acct.hello();
}
}
I suppose it contradicts to the specification where we can find:
It is a compile-time error if an attempt is made to create an instance of an abstract
class using a class instance creation expression (§15.9).
You may have not noticed the difference:
new AbstractClassCreationTest(){};
versus
new AbstractClassCreationTest();
That extra {} is the body of a new, nameless class that extends the abstract class. You have created an instance of an anonymous class and not of an abstract class.
Now go ahead an declare an abstract method in the abstract class, watch how compiler forces you to implement it inside {} of anonymous class.
Notice the difference between:
AbstractClassCreationTest acct = new AbstractClassCreationTest(){};//case 1
NonAbstractClassCreationTest acct = new NonAbstractClassCreationTest();//case 2
case1 is an anonymous class definition. You are not instantiating an abstract class; instead you are instantiating a subType of said abstract class.
Here you are not creating the object of the AbstractClassCreationTest class , actually you are creating an object of anonymous inner class who extends the AbstractClassCreationTest class.This is because you have written new AbstractClassCreationTest(){} not new AbstractClassCreationTest()
You can know more about anonymous inner class from here
An abstract class cannot instantiated.
You must create an extension class extends an abstract class and so istantiated this new class.
public abstract class AbstractClassCreationTest {
public void hello(){
System.out.println("I'm the abstract class' instance!");
}
}
public class MyExtClass extends AbstractClassCreationTest() {
}
public static void main(String[] args) {
MyExtClass acct = new MyExtClass(){};
acct.hello();
}
I post this. Can be useful for you. Have a nice day
Related
This question already has answers here:
Superclass reference not able to call subclass method in Java
(2 answers)
Closed 2 years ago.
abstract class superclass {
public abstract void method();
}
class subclass extends superclass {
public void method() {
//do something
}
public void newMethod() {
//do something
}
}
public class mainclass {
public static void main(String[]args) {
superclass abc = new subclass();
abc.method();
abc.newMethod(); //cannot find symbol error
}
}
In the above example, can new methods be not written in the derived class of an abstract class? If I do that, it raises an error.
When extending a Superclass you can in fact add more methods. Hoevery in this case you assign your new subclass() to a variable of the type superclass which means that you will only have access to the methods wich are a part of that type. In this case that's only method(). If you want to use both methods you should write instead:
subclass abc = new subclass();
or cast it on demand:
((subclass) abc).newMethod();
This question already has answers here:
Can we instantiate an abstract class?
(16 answers)
Closed 7 years ago.
abstract class A {
public void disp() {
System.out.print("Abstract");
}
}
public class B {
public static void main(String args[]) {
A object = new A(){ };
object.disp();
}
}
I am aware that Abstract classes cannot be instantiated, but confused on this code.
Actually what this code mean ?
The subtlety here is in the "{}". It means you explicitly provide an anonymous implementation for the missing parts (the missing parts are abstract methods) of the abstract class A allowing you to instantiate it.
But there's no abstract method in A, therefore the anonymous implementation is empty.
Example showing the behaviour with at least one abstract method:
public abstract class A {
public abstract void bar();
public void disp() { System.out.print("Abstract"); }
}
public class B {
public static void main(String args[]) {
A object = new A() {
#Override public void bar() { System.out.print("bar"); }
};
object.disp(); //prints "Abstract"
object.bar(); //prints "bar"
}
}
This is called an anonymous inner class. You are not instantiating the abstract class, you are instantiating the concrete anonymous inner class which extends the abstract class. Of course, in order for this to be allowed, the anonymous inner class must provide implementations for all the abstract members of the abstract superclass … which it does in this case, because the abstract superclass has no abstract members.
Okay, people are probably going to run to flag this as a duplicate, just by reading the title and without really reading the question. So please know that I HAVE tried to look at other questions on this platform, but have not found something that clears my doubts exactly. Kindly allow me to reach out and ask my question. Thanks in advance.
Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
I do not completely understand the latter part of the statement. Is this talking about the main method being directly within the abstract class itself ? Is it talking about invoking the abstract class via a child's main method ? Or both ?
Secondly, I have seen examples like the following.
abstract class Printer
{
public void print() { … };
}
public class TestPrinter
{
public static void main( String[] args )
{
// use of anonymous class
final Printer p = new Printer()
{
#override
public void print()
{
...
}
}
}
}
And have been told that an anonymous class is at work. But, I seriously do not understand how, since the variable 'p' is clearly being assigned to... and it's an abstract class variable!! How is that even possible? I thought abstract classes can not be instantiated or initialized.
Any help would be appreciated.
final Printer p = new Printer()
{
#override
public void print()
{
...
}
}
This means that an anonymous class is created which extends Printerand the variable p is referring to subclass instance.
This is simply polymorphism in action. By creating anonymous class here, you are creating a subclass of Printer and using polymorphism you are using the superclass reference variable p to refer to object of subclass which is anonymous but extends Printer because of the syntax below
Printer p = new Printer(){...}
and this is not only limited to abstract class, you can also create an anonymous class which implements and interface. Consider below example.
package com.test;
public interface SomeInterface {
public void SomeMethod();
}
and a class below
package com.test;
public class TestAnonymous {
public static void main(String[] args) {
SomeInterface obj = new SomeInterface() {
#Override
public void SomeMethod() {
System.out
.println("Yaayy!!! Creating an anonymous class which implements SomeInterface ");
}
};
obj.SomeMethod();
}
}
which prints out
Yaayy!!! Creating an anonymous class which implements SomeInterface
What is means that the syntax creates an anonymous class which either extends the abstract class or implements the interface of which reference variable is used to instantiate. It calls method of the subclass.
You can refer jsl.https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.1
Now your question
Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists
What I understand from your questions is whether you want to know whether main method can be run in abstract class without instantiating it, The answer is YES
package com.test;
public abstract class AbstractClass {
public static void main(String[] args) {
System.out.println("main method in abstract class");
}
}
compile and invoke it using java AbstractClass and it should print
main method in abstract class
IF you want to know whether the abstract class constructor is invoked when instantiating the anynomous class or not, then also the answer is YES.
Whenver a subclass constructor is called, it invokes super class constructor by making a super() call. So abstract class constructor will also get called.
http://www.thejavageek.com/2013/07/21/initialization-blocks-constructors-and-their-order-of-execution/
An abstract class is just like any other class - except for the fact that it cannot be instantiated directly. I presume you know the use for such a facility. Hence it can very well have a main(), which is a static method, not an instance method
The anonymous class in your example, extends the abstract class (or implements an interface, if one is specified). So p is not assigned to an abstract class instance, but to an instance of a class which extends the abstract class
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
It is nonsense. Any static method of an abstract class can be invoked. Not just main().
Secondly, I have seen examples like the following ... and have been told that an anonymous class is at work.
That is correct.
But, I seriously do not understand how, since the variable 'p' is clearly being assigned to... and it's an abstract class variable!! How is that even possible? I thought abstract classes can not be instantiated or initialized.
It is the anonymous class that is being instantiated here, which extends the abstract class, and provides an implementation of the abstract method. The reference to that class is being stored into Person p, because Person is a superclass of the anonymous class. You can do that for any other class or interface. There's nothing new here.
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
Since main() method is static an can be invoked without instantiation. e.g.
abstract class AbstractClass{
public static void main(String[] args){
}
}
The same was not true for interface till Java7, With Java8 you can have static main method inside interface hence same would be true for Java8
You second question, while creating an instance of Printer you have defined the sub-class of Printer as well but you can not use this defined implementation of Printer again(since there is no name associated with the implementation), Hence, its anonymous.
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interview : Can we instantiate abstract class?
I have an abstract class with all its methods defined (i.e. there are no abstract methods contained within it) like the following:
public abstract class MyAbstractClass {
String s;
public void setString(String s) {
this.s = s;
}
public String getString() {
return this.s;
}
}
There is also a JUnit test class:
public class TestClass {
MyAbstractClass c;
#Before
public void setUp() {
// What is happening here? And why does this work with an abstract class?
// Instantiation? Extending the abstract class? Overwriting?
c = new MyAbstractClass() { };
// This will not work: (Why?)
// c = new MyAbstractClass();
}
#Test
public void test_AllMethodsAvailable() {
// Why can I access the abstract class' methods?
// Shouldn't they be overwritten? Or did I extend the class?
c.setString("Test");
assertEquals("Test", c.getString());
}
}
I don't quite understand why the assignment to c works in the first case but not in the second, or what is actually happening there (and as a consequence, why accessing the abstract class' methods works in the test).
Can somebody please explain (and possibly point me to a Javadoc, article or book that explains why this works)?
Why can I "instantiate" an abstract class there? (Is that actually what I'm doing?)
Has it to do with inner classes?
You are creating an anonymous inner class with that code. The class you create this way is implicitly extending MyAbstractClass.
Since your abstract class does not have abstract methods you don't have to provide implementations so this works.
If you don't know about inner classes you can check the official documentation which is quite nice I think.
Has it to do with inner classes?
c = new MyAbstractClass() { };
Absolutely, the above is anonymous inner class declaration, you are not really instantiating an abstract class(which you can't) here but you are actually creating an Anonymous inner class(a sub-type of MyAbstractClass)
When you write c = new MyAbstractClass() { };, you actually create an anonymous class which extends MyAbstractClass, and which is not abstract. Since MyAbstractClass already has all method defined, the instanciation is valid.
Your assignment to c works because you are subclassing MyAbstractClass with an anonymous non-abstract class, the c is an instance of the non-abstract class.
Since you don't have any abstract methods in your abstract class, your anonymous class doesn't have to implement anything.