Check attribute of a subclass

后端 未结 3 852
甜味超标
甜味超标 2021-01-26 09:44

I stumbled across that situation but I don\'t know how to handle it the right way:

class Myclass { }
class MyclassWithAwesomeStuff extends Myclass {
    public b         


        
相关标签:
3条回答
  • 2021-01-26 09:52

    Just use an interface:

    interface AwesomeStuffable{
    
        public boolean isAwesome();
    
    }
    

    let your classes implement it:

    class MyClass implements AwesomeStuffable{
    
      public boolean isAwesome(){
    
        //your logic here
    
      }
    
    }
    

    And let your ArrayList hold just AwesomeStuffable objects.

    0 讨论(0)
  • 2021-01-26 09:52

    Just to get yourself unblocked, you can do the following:

    if (m instanceof MyClassWithAwesomeStuff) {
        if (((MyClassWithAwesomeStuff) m).awesomeStuff) {
    
        }
    }
    

    But, using instanceof defeats the purpose of inheritance and it appears to be a design flaw to have a need to check for this flag for only some objects in list in your code. If you expand the context, probably something better can be suggested.

    0 讨论(0)
  • 2021-01-26 10:01

    Test if m is a MyclassWithAwesomeStuff with the instanceof operator.

    if (m instanceof MyclassWithAwesomeStuff)
    {
        MyclassWithAwesomeStuff mwas = (MyclassWithAwesomeStuff) m;
        // Now you can access "awesomeStuff" with "mwas"
    }
    
    0 讨论(0)
提交回复
热议问题