Note that there are some explanatory texts on larger screens.

plurals
  1. POInstantiating abstract classes in Java: Why does this work?
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/13670991/interview-can-we-instantiate-abstract-class">Interview : Can we instantiate abstract class?</a> </p> </blockquote> <p>I have an abstract class with all its methods defined (i.e. there are no abstract methods contained within it) like the following: </p> <pre class="lang-java prettyprint-override"><code>public abstract class MyAbstractClass { String s; public void setString(String s) { this.s = s; } public String getString() { return this.s; } } </code></pre> <p>There is also a JUnit test class:</p> <pre class="lang-java prettyprint-override"><code>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()); } } </code></pre> <p>I don't quite understand why the assignment to <code>c</code> 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). </p> <p>Can somebody please explain (and possibly point me to a Javadoc, article or book that explains why this works)? </p> <p>Why can I "instantiate" an abstract class there? (Is that actually what I'm doing?) </p> <p>Has it to do with inner classes?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload