Search code examples
javavariablesstaticsubclasssuperclass

why do I keep getting errors when I try to use getters to access a List I created as an instance variable for my superclass?


This is my code for the Powers superclass:

import java.util.*;

public abstract class Powers implements Sequence
{
   private ArrayList<Double> powers;

   public Powers()
   {
      powers = new ArrayList<Double>(); 
   }

   public abstract List<Double> firstTenTerms();
   public abstract List<Double> firstNTerms(int n); 

   public void setPowers(ArrayList<Double> newlist)
   {
      powers = newlist;
   }

   public List<Double> getPowers()
   {
      return powers;
   }
}

And below is my code for PowersofTwo Subclass (well, part of it, since the code is quite long): import java.util.*;

public class PowersOfTwo extends Powers
{   
   public PowersOfTwo()
   {
      super();
   }

   public List<Double> firstTenTerms()
   {
      if(Powers.getPowers().size()!=0)
      {
         while(Powers.getPowers().size()>0)
         {
            Powers.getPowers().remove(powers.size()-1);
         }
      }

      for(int k=0; k<10; k++)
      {
         Powers.getPowers().add(Math.pow(2.0,(double) k));
      }
      return Powers.getPowers();
   }
}

When I try to compile the subclass, I keep on getting this kind of error message:

PowersOfTwo.java:15: error: non-static method getPowers() cannot be referenced from a static context

Or, if I just try "powers" rather than "Powers.getPowers()", I still get this:

PowersOfTwo.java:19: error: powers has private access in Powers

The problems I had encountered in classes were usually solved by using the getters, and now I am really stumped as to what to do to try fix this error. Any help would really be appreciated!


Solution

  • In abstract class Powers, you have a non-static method called getPowers(). To access it, you must use an instance of a class that extends Powers. Perhaps you wanted to make getPowers() a static method?

    Or you could declare the "powers" variable as protected instead of private, then use "powers".