Java: How to refer to subclass's static variable in abstract class? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Java: static field in abstract classIs Java “pass-by-reference” or “pass-by-value”?Are static class variables possible?Java inner class and static nested classHow do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?Why can't static methods be abstract in JavaDifference between static class and singleton pattern?Interface vs Abstract Class (general OO)What is the difference between an interface and abstract class?How do I convert a String to an int in Java?

How long can equipment go unused before powering up runs the risk of damage?

Semigroups with no morphisms between them

How do living politicians protect their readily obtainable signatures from misuse?

Is multiple magic items in one inherently imbalanced?

Drawing spherical mirrors

What's the point of the test set?

One-one communication

What does Turing mean by this statement?

Girl Hackers - Logic Puzzle

Converted a Scalar function to a TVF function for parallel execution-Still running in Serial mode

Significance of Cersei's obsession with elephants?

What order were files/directories output in dir?

Random body shuffle every night—can we still function?

Why does it sometimes sound good to play a grace note as a lead in to a note in a melody?

Why are vacuum tubes still used in amateur radios?

How were pictures turned from film to a big picture in a picture frame before digital scanning?

How much damage would a cupful of neutron star matter do to the Earth?

Does the Mueller report show a conspiracy between Russia and the Trump Campaign?

What does 丫 mean? 丫是什么意思?

How can I prevent/balance waiting and turtling as a response to cooldown mechanics

Tannaka duality for semisimple groups

Do wooden building fires get hotter than 600°C?

How does Belgium enforce obligatory attendance in elections?

Did any compiler fully use 80-bit floating point?



Java: How to refer to subclass's static variable in abstract class?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Java: static field in abstract classIs Java “pass-by-reference” or “pass-by-value”?Are static class variables possible?Java inner class and static nested classHow do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?Why can't static methods be abstract in JavaDifference between static class and singleton pattern?Interface vs Abstract Class (general OO)What is the difference between an interface and abstract class?How do I convert a String to an int in Java?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I understand, thanks to this question, that the value of a static field declared in an abstract class will be the same among all subclasses.



The solution in the aforementioned question is to declare a static field in each subclass, and an abstract "getter" instance method in the abstract class that must be implemented by each subclass.



But I have a static method in my abstract class, and I need to refer to the static field of the subclass. I can't do this because the getter is an instance method.



What's the best solution here? I'd rather not put nearly identical instances of getAll in every subclass.



public abstract class AbstractModel 

public abstract String getTableName();

public static ResultSet getAll()

Statement stmt = Database.get().conn.createStatement();

// Error below: Cannot use "this" in static context.
String query = "SELECT * FROM `" + this.getTableName() + "`";

return stmt.executeQuery(query);




public class Api extends AbstractModel

protected static final String TABLE_NAME = "apis";

@Override
public String getTableName()
return TABLE_NAME;












share|improve this question






















  • If you want a different value for each subclass, why make it static in the first place?

    – Tiberiu
    Mar 8 at 22:07











  • Given that getAll() is static, it doesn't have any context. If you write Api.getAll(), that resolves to the same bytecode as AbstractModel.getAll() - there's no concept of calling the static method "on" the subclass. Perhaps you need to have a second class hierarchy, of AbstractTable, ApiTable etc...

    – Jon Skeet
    Mar 8 at 22:08

















1















I understand, thanks to this question, that the value of a static field declared in an abstract class will be the same among all subclasses.



The solution in the aforementioned question is to declare a static field in each subclass, and an abstract "getter" instance method in the abstract class that must be implemented by each subclass.



But I have a static method in my abstract class, and I need to refer to the static field of the subclass. I can't do this because the getter is an instance method.



What's the best solution here? I'd rather not put nearly identical instances of getAll in every subclass.



public abstract class AbstractModel 

public abstract String getTableName();

public static ResultSet getAll()

Statement stmt = Database.get().conn.createStatement();

// Error below: Cannot use "this" in static context.
String query = "SELECT * FROM `" + this.getTableName() + "`";

return stmt.executeQuery(query);




public class Api extends AbstractModel

protected static final String TABLE_NAME = "apis";

@Override
public String getTableName()
return TABLE_NAME;












share|improve this question






















  • If you want a different value for each subclass, why make it static in the first place?

    – Tiberiu
    Mar 8 at 22:07











  • Given that getAll() is static, it doesn't have any context. If you write Api.getAll(), that resolves to the same bytecode as AbstractModel.getAll() - there's no concept of calling the static method "on" the subclass. Perhaps you need to have a second class hierarchy, of AbstractTable, ApiTable etc...

    – Jon Skeet
    Mar 8 at 22:08













1












1








1


1






I understand, thanks to this question, that the value of a static field declared in an abstract class will be the same among all subclasses.



The solution in the aforementioned question is to declare a static field in each subclass, and an abstract "getter" instance method in the abstract class that must be implemented by each subclass.



But I have a static method in my abstract class, and I need to refer to the static field of the subclass. I can't do this because the getter is an instance method.



What's the best solution here? I'd rather not put nearly identical instances of getAll in every subclass.



public abstract class AbstractModel 

public abstract String getTableName();

public static ResultSet getAll()

Statement stmt = Database.get().conn.createStatement();

// Error below: Cannot use "this" in static context.
String query = "SELECT * FROM `" + this.getTableName() + "`";

return stmt.executeQuery(query);




public class Api extends AbstractModel

protected static final String TABLE_NAME = "apis";

@Override
public String getTableName()
return TABLE_NAME;












share|improve this question














I understand, thanks to this question, that the value of a static field declared in an abstract class will be the same among all subclasses.



The solution in the aforementioned question is to declare a static field in each subclass, and an abstract "getter" instance method in the abstract class that must be implemented by each subclass.



But I have a static method in my abstract class, and I need to refer to the static field of the subclass. I can't do this because the getter is an instance method.



What's the best solution here? I'd rather not put nearly identical instances of getAll in every subclass.



public abstract class AbstractModel 

public abstract String getTableName();

public static ResultSet getAll()

Statement stmt = Database.get().conn.createStatement();

// Error below: Cannot use "this" in static context.
String query = "SELECT * FROM `" + this.getTableName() + "`";

return stmt.executeQuery(query);




public class Api extends AbstractModel

protected static final String TABLE_NAME = "apis";

@Override
public String getTableName()
return TABLE_NAME;









java static abstract-class static-methods






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 21:23









Cameron HudsonCameron Hudson

15437




15437












  • If you want a different value for each subclass, why make it static in the first place?

    – Tiberiu
    Mar 8 at 22:07











  • Given that getAll() is static, it doesn't have any context. If you write Api.getAll(), that resolves to the same bytecode as AbstractModel.getAll() - there's no concept of calling the static method "on" the subclass. Perhaps you need to have a second class hierarchy, of AbstractTable, ApiTable etc...

    – Jon Skeet
    Mar 8 at 22:08

















  • If you want a different value for each subclass, why make it static in the first place?

    – Tiberiu
    Mar 8 at 22:07











  • Given that getAll() is static, it doesn't have any context. If you write Api.getAll(), that resolves to the same bytecode as AbstractModel.getAll() - there's no concept of calling the static method "on" the subclass. Perhaps you need to have a second class hierarchy, of AbstractTable, ApiTable etc...

    – Jon Skeet
    Mar 8 at 22:08
















If you want a different value for each subclass, why make it static in the first place?

– Tiberiu
Mar 8 at 22:07





If you want a different value for each subclass, why make it static in the first place?

– Tiberiu
Mar 8 at 22:07













Given that getAll() is static, it doesn't have any context. If you write Api.getAll(), that resolves to the same bytecode as AbstractModel.getAll() - there's no concept of calling the static method "on" the subclass. Perhaps you need to have a second class hierarchy, of AbstractTable, ApiTable etc...

– Jon Skeet
Mar 8 at 22:08





Given that getAll() is static, it doesn't have any context. If you write Api.getAll(), that resolves to the same bytecode as AbstractModel.getAll() - there's no concept of calling the static method "on" the subclass. Perhaps you need to have a second class hierarchy, of AbstractTable, ApiTable etc...

– Jon Skeet
Mar 8 at 22:08












1 Answer
1






active

oldest

votes


















0














I was able to write the code in this way, to minimize repitition. It also eliminates the need for a getter.



public abstract class AbstractModel 

public static ResultSet getAllFromTable(String tableName)

Statement stmt = Database.get().conn.createStatement();

String query = "SELECT * FROM `" + tableName + "`";

return stmt.executeQuery(query);




public class Api extends AbstractModel

protected static final String TABLE_NAME = "apis";

public static ResultSet getAll()
return getAllFromTable(TABLE_NAME);








share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071196%2fjava-how-to-refer-to-subclasss-static-variable-in-abstract-class%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I was able to write the code in this way, to minimize repitition. It also eliminates the need for a getter.



    public abstract class AbstractModel 

    public static ResultSet getAllFromTable(String tableName)

    Statement stmt = Database.get().conn.createStatement();

    String query = "SELECT * FROM `" + tableName + "`";

    return stmt.executeQuery(query);




    public class Api extends AbstractModel

    protected static final String TABLE_NAME = "apis";

    public static ResultSet getAll()
    return getAllFromTable(TABLE_NAME);








    share|improve this answer



























      0














      I was able to write the code in this way, to minimize repitition. It also eliminates the need for a getter.



      public abstract class AbstractModel 

      public static ResultSet getAllFromTable(String tableName)

      Statement stmt = Database.get().conn.createStatement();

      String query = "SELECT * FROM `" + tableName + "`";

      return stmt.executeQuery(query);




      public class Api extends AbstractModel

      protected static final String TABLE_NAME = "apis";

      public static ResultSet getAll()
      return getAllFromTable(TABLE_NAME);








      share|improve this answer

























        0












        0








        0







        I was able to write the code in this way, to minimize repitition. It also eliminates the need for a getter.



        public abstract class AbstractModel 

        public static ResultSet getAllFromTable(String tableName)

        Statement stmt = Database.get().conn.createStatement();

        String query = "SELECT * FROM `" + tableName + "`";

        return stmt.executeQuery(query);




        public class Api extends AbstractModel

        protected static final String TABLE_NAME = "apis";

        public static ResultSet getAll()
        return getAllFromTable(TABLE_NAME);








        share|improve this answer













        I was able to write the code in this way, to minimize repitition. It also eliminates the need for a getter.



        public abstract class AbstractModel 

        public static ResultSet getAllFromTable(String tableName)

        Statement stmt = Database.get().conn.createStatement();

        String query = "SELECT * FROM `" + tableName + "`";

        return stmt.executeQuery(query);




        public class Api extends AbstractModel

        protected static final String TABLE_NAME = "apis";

        public static ResultSet getAll()
        return getAllFromTable(TABLE_NAME);









        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 22:13









        Cameron HudsonCameron Hudson

        15437




        15437





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071196%2fjava-how-to-refer-to-subclasss-static-variable-in-abstract-class%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко