Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I believe you are making the same mistake I made when I was starting out: that the abstract class and the extending class are two piece welded together to form a single class with access to all of each others fields and methods etc.</p> <p>Sadly, this is not true: inheritance is a closer relationship that in a normal parent-child object, but access rules must still be obeyed e.g. if a method is declared <code>protected</code> in the abstract class and the extending class is in a different package, then it cannot be accessed (and vice versa).</p> <p>Because the method <code>showFields()</code> is defined in <code>AbstractTestClass</code>, it can only access the fields in that class. Fields in <code>TestClass</code> are essentially walled off.</p> <p>The only way around it that I can think of is to override <code>showFields()</code> in <code>TestClass</code>, swallow any exceptions about not being able to access private fields, then call <code>super.showFields()</code> and swallow any exceptions again. Not pretty.</p> <pre><code>public abstract class AbstractTest { private String abstractString = "abstract"; public void showFields() throws IllegalAccessException { for (Field field : this.getClass().getSuperclass().getDeclaredFields()) { try { System.out.println(field.get(this)); } catch (IllegalAccessException e) { // swallow } } } } public class MyTest extends AbstractTest { private String concreteString = "concreteString"; @Override public void showFields() throws IllegalAccessException { for (Field field : this.getClass().getDeclaredFields()) { try { System.out.println(field.get(this)); } catch (IllegalAccessException e) { // swallow } } super.showFields(); } } </code></pre> <p>I doubt this is what you had in mind...</p>
    singulars
    1. This table or related slice is empty.
    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