-3

I still don't understand what really an object is , we all know that an object is the instance of a certain class(blue print), see the following:

class A{
   static int x ;
   int  y;

   static void meth1(){
    int a;
   }

   void meth2(){
     int b; 
   }  

}

I've read from many resources that:

  • static ,non-static methods and their local variables are stored in the stack.
  • static variables are stored in the heap.
  • the object is stored in the heap.
  • instance variables are stored with the object in the heap.

But questions are :

  • what is really the object?
  • depending on the example above , could you give me a divide between members that go on the heap and others on the stack ?

Thanks in advance,

4 Answers4

1

what is really the object?

Objects in Java are similar to objects in real world. Real objects have their states/characteristics and behaviours. In java the characteristics/state are fields and behaviour are implemented methodes that an object possess.

e.g. A dog is an object and has its age, colour, can be in particular mood etc. These are states of dog. The behaviours (methodes) are bark, changing mood(if you pet him) etc.

class Dog{
      int age;
      String colour;
      String mood;

      public void Bark(){
         System.out.print("ruff");
       }

      public void pet(String newMood){
         this.mood=newMood;
      }
}

Think of an Java object as a real world object, that should help.

wizzle
  • 215
  • 2
  • 3
  • 7
0

int a and int b will be in a stack, while everything else in a heap

The difference between int x and int y is that memory is allocated for the former when the class is loaded, while for the latter it's when an object of class A is created.

The tricky and interesting thing is that Class is an object too in Java that you can get through Object.getClass() method.

You can find more details here: where is a static method and a static variable stored in java. In heap or in stack memory

BTW, methods are not stored on a stack as some answers below have suggested.

Community
  • 1
  • 1
Oleg Gryb
  • 5,122
  • 1
  • 28
  • 40
0

Stack: methods, local variables, variable references

Heap: objects and its variables

Dávid Szabó
  • 2,235
  • 2
  • 14
  • 26
0

An object is just an abstraction. As such, it's a tool for you to do whatever you want with it.

what is really the object?

This is the wrong question to ask. Or rather, the real answer is that it's whatever you want it to be. The real question is, which abstractions do you need to make your computer program work easily?

FrobberOfBits
  • 17,634
  • 4
  • 52
  • 86