Access to class variables of an internal object

In my main class, I have an inner Shape class that extends JButton. This inner class has a private variable called char called CUBE.

I wrote getters and setters for this. I noticed that in the main method, instead of using:

(instance of Shape).getCUBE(); 

I can access it using:

(instance of Shape).CUBE

Is this because CUBE ends up in the same class as the main one?

Do I need to write getters and setters for such an inner class using java software conventions?

+3
source share
3 answers

Is this because CUBE ends up in the same class as the main one?

, , , . JVM, , .

6.6.1:

, , , (§7.6), .

( .)

, . :

public class Test {

    public static void main(String[] args) {
        First first = new First(10);
        Second second = new Second(first);
        System.out.println(second.getValueFromFirst());
    }

    private static class First {        
        private final int value;

        private First(int value) {
            this.value = value;
        }
    }

    private static class Second {
        private final First first;

        private Second(First first) {
            this.first = first;
        }

        private int getValueFromFirst() {
            return first.value;
        }
    }
}

( javap -c Test$First javap -c Test$Second, , .

+7

, :

import javax.swing.JButton;

class Main
{
   public class Shape extends JButton
   {
      private char CUBE = 'I';

      public char getCUBE()
      {
             return CUBE;
      }
      public void setCUBE(char CUBE){this.CUBE = CUBE;}
   }

   public static void main(String[] args) 
   {
      Shape sp = new Main().new Shape();
      System.out.println(sp.CUBE);
      System.out.println(sp.getCUBE());
   }
}

public class TestMain
{
    public static void main(String[] args) 
    {
     Main.Shape sp = new Main().new Shape();
     //System.out.println(sp.CUBE);
     System.out.println(sp.getCUBE());
    }
}

, . , CUBE Main, getter setter.

0

This works because you forgot to add a keyword private.

-3
source

All Articles