[转载]JAVA内存分析——栈、堆、方法区 程序执行变化过程

面向对象的内存分析

参考:http://www.sxt.cn/Java_jQuery_in_action/object-oriented.html

;尚学堂JAVA300集-064内存分析详解_栈_堆_方法区_栈帧_程序执行的内存变化过程;

 

栈:用于存放局部变量;一个线程一个栈,线程间不能共享;在一个线程中每个方法都有一个栈帧;

 堆:用于存放创建好的对象,一个对象在堆中开辟一块;JVM只有一个堆,所有线程共享;

方法区(也是堆):用于存储类信息、静态变量、字符串常量;运行时,会将所有类信息在方法区内一次加载完。

例一

代码:

SxtStu.java

public class SxtStu {
    
    //属性fields
    int  id;
    String  sname;
    int  age;
    
    Computer  comp;  //计算机
    
    //方法
    void  study(){
        System.out.println("我在认真学习!!,使用电脑:"+comp.brand);
    }
    
    void  play(){
        System.out.println("我在玩游戏!王者农药!"); 
    }
    
    //构造方法。用于创建这个类的对象。无参的构造方法可以由系统自动创建。
    SxtStu(){
        System.out.println("调用了无参的构造方法!");
    }
    
    //程序执行的入口,必须要有
    //javac  Sxtstu.java   ,   java Sxtstu
    public static void main(String[] args) {
        SxtStu  stu = new SxtStu();   //创建一个对象
        stu.id=1001;
        stu.sname= "高淇";
        stu.age = 18;
        
        Computer  c1 = new Computer();
        c1.brand = "联想";
        
        stu.comp = c1;
        
        stu.play();
        stu.study();
        
    }
}

class  Computer {
    String  brand;
}

图解:

例二

代码:

Animal.java

package cn.bjsxt.oop.polymorphism;

public class Animal {
    String str;
    public void voice(){
        System.out.println("普通动物叫声!");
    }
}

class Cat extends Animal {
    public void voice(){
        System.out.println("喵喵喵");
    }
    public void catchMouse(){
        System.out.println("抓老鼠");
    }
}

class Dog extends Animal {
    public void voice(){
        System.out.println("汪汪汪");
    }
    
    public void seeDoor(){
        System.out.println("看门!");
    }
    
}

class Tiger extends Animal {
    public void voice(){
        System.out.println("哇哇哇");
    }

    
}

class Pig extends Animal {
    public void voice(){
        System.out.println("哼哼哼");
    }
}

Test.java

package cn.bjsxt.oop.polymorphism;

public class Test {
    
    public static void testAnimalVoice(Animal c){
        c.voice();
        if(c instanceof Cat){
            ((Cat) c).catchMouse();
        }
    }
    
    /*
    public static void testAnimalVoice(Dog c){
        c.voice();
    }
    
    public static void testAnimalVoice(Pig c){
        c.voice();
    }*/
//javac Test.java    
//    java Test
    public static void main(String[] args) {
        Animal a = new Cat();
        Cat a2 = (Cat)a;
        testAnimalVoice(a);

//        a2.catchMouse();

//        Animal b = new Dog();
//        Animal c = new Tiger();
//        testAnimalVoice(b);
//        testAnimalVoice(c);
        
    }
}

图解:   *this指向最终的Cat类对象

原文地址:https://www.cnblogs.com/musecho/p/10740349.html