Inheritance For Variables

0 Developer John · September 23, 2014
Ok, before I show you my code, remember, I don't know how to inherit variables. I don't know if it is different from inheriting strings or not. With that being stated, here is my main class called Tuna:
package me.wizard7611.Inheritance;

public class Tuna{
    
    public static void main(String[] args){
        
        Apples appleObject = new Apples();
        
        appleObject.food();
        
        System.out.println(cookie);
    //System.out.println(cookie); gives me an error saying "Cookie cannot be resolved as a variable"
    }

}


My subclass:
package me.wizard7611.Inheritance;

public class Apples {
    
    private void food(){
        int cookie = 4;
    }

}


Why exactly do I get the error and how can I solve it? 

-Thanks!8-)

Post a Reply

Replies

- page 2
Oldest  Newest  Rating
0 Developer John · September 23, 2014
Lol calm down, I was just doing that for a simple test, not logically doing it or following Bucky (Greg).
+1 Patrick Lehmann · September 23, 2014
Besides the way he names the variables

There is, at least as far as I know, no way to inherit variables within Java. No Pointers no nothing. A simple way to do this would be via getters

So your new Apple class would look something like this

package me.wizard7611.Inheritance;

public class Apples {
   
   private int cookie;

   private void food(){
       this.cookie = 4;
   }

public int getCookies() {
  return this.cookie;
  }
}



and in your Tuna class


package me.wizard7611.Inheritance;

public class Tuna{
   
   public static void main(String[] args){
       
       Apples appleObject = new Apples();
       
       appleObject.food();
       // Call the getter to "get" the variable
       int cookie = appleObject.getCookies();
       System.out.println(cookie);
   // Now this will print out 4
   }

}
  • 1
  • 2

Java / Android Development

129,789 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator