Object Oriented Programming

来源:互联网 发布:安安电子狗软件 编辑:程序博客网 时间:2024/04/26 13:36

1. Main memory analysis

When Programs executes, the main memory is devided into 4 parts:

Code section: store the programs

Data section: store data

Heap: store the object created by the "new" key word

Stack: store simple data type.

main memoryCode SectionHeapData SectionStack

For example, here comes an program:

public class Dog{ String color = "red"; int age = 2;  public void run(){    int i;    Dog d1 = new Dog();    Dog d2 = new Dog();    System.out.println("run");  }}
First:

when an line of code executes "String s;", the system allocate a small part of location in Stack, but the value is null. When it executes to s = "hello world", since String is an object, so in the heap section, there will be a place arranged for the object, and at this time, the s will has it's value, which is the location of "hello world".

Second:

Every object in the Heap like d1, only has its data field, not method. There is only one method which is in the Dog class and in the Code Section. The system will not arrange location for the method in Heap until it is called by the instance.

Third:

d1 and d2 are in the stack section, they contain the address pointing to their own instance.


2. Subclass instance Memory analysis

package test;public class A2Demo {   public static void main(String[] args) {  new Koo();     }}class Foo { int i=10; int j=10; public Foo(){ this.test(); } public void test(){ System.out.println("****foo****"); }}class Koo extends Foo{   int i=3 ;   public void test(){  System.out.println(i); System.out.println(j);   }   }

 

OutPut: 0, 10

Analysis:

when we instance a class, The sequence is

Step 1: allocate a place for the instance variables in the stack, and give them the default value.

            ( the default values are null for object variables and 0 for all base types except boolean variables)

Step 2: goes to super class to allocate instance varibales until it goes to Object class.

Step 3: The constructor for the new object is called with the parameters specified.The  constructor fills in meaningful values for the instance variables.

Step 4: give value to the data field according to the parameter from the constructor.

So, here, we first new Koo instance which will sign a data field in stack for int i, default value is 0. then before it goes to default constructor, since it is extend from Foo class, it has to realize Foo's data field and methods. So it allocates field for Foo's variable i and j, and allocate the default value 0 to both of them.then goes to Foo's super class until the Object class, and then goes back to allocate value to Foo's i and j. then do Foo's constructor. Then allocate value to Koo's data field then do Koo's constructor. 

 

So, the result is i=0( is Koo's variable, which has not been allocated data 3 yet. ), j =10(j is extended from Foo)