java继承的内存分析

编程入门 行业动态 更新时间:2024-10-13 08:24:02

java继承的<a href=https://www.elefans.com/category/jswz/34/1771154.html style=内存分析"/>

java继承的内存分析

package day03;

/*

* 继承时候对象的创建过程

* 1 Java首先递归加载所有类搭配方法区

* 2 分配父子类型的内存(实例变量)

* 3 递归调用构造器

*/

public class Demo01 {

public static void main(String[] args) {

Goo g = new Goo();

System.out.println(g.a+","+g.b+","+g.c);

}

}

class Foo{

int a = 1;

public Foo(){a = 5;}

}

class Koo extends Foo{

int b = 2;

public Koo(){super();b=6;a=7;}

}

class Goo extends Koo{

int c = 3;

public Goo(){super();a=8;b=9;c=10;}

}

package day03;

/*

* 方法动态绑定到运行期间对象的方法

*/

public class Demo02 {

public static void main(String[] args) {

Moo moo = new Noo();//父类型变量引用了子类对象

moo.test();//父类型Moo上声明的方法,子类型重写的方法

//动态绑定到Noo对象,执行Noo对象的方法

}

}

class Moo{

public void test(){

System.out.println("Moo test()");

}

}

class Noo extends Moo{

public void test(){

System.out.println("Noo test()");

}

}

package day03;

/*

* 类一定有构造器,默认构造器,会自动调用父类的无参数构造器

*/

public class Demo03 {

public static void main(String[] args) {

Boo b = new Boo();

}

}

class Aoo{

int a= 1;

public Aoo(){this.test();}//父类里的构造器执行初始化

public void test(){

System.out.println("Aoo" + a);

}

}

class Boo extends Aoo{

int b = 2;

public Boo(){super();}//默认构造器,写不写都存在

public void test(){

System.out.println("Boo " +a + ","+b);

}

}

package day03;

/*

* 属性绑定到变量的类型,由变量类型决定访问哪个属性

* 方法动态绑定到对象,由对象的类型决定访问哪个方法

*/

public class Demo04 {

public static void main(String[] args){

Cheater c = new Cheater();//方法动态绑定到对象的方法

Person p = c;//先分配父类型空间,再分配子类

System.out.println(p.name+","+c.name);//由变量类型决定访问哪个属性

p.whoau();

c.whoau();

}

}

class Person{

String name = "灰太狼";

public void whoau(){

System.out.println(this.name);

}

}

class Cheater extends Person{//Cheater:骗子

String name = "喜羊羊";

public void whoau() {

System.out.println(name);

}

}

package day03;

public class Demo05 {

public static void main(String[] args) {

Woo w = new Woo();

Super s = new Sub();

w.t(s);//重载的方法调用由参数s类型Super决定,与对象Sub无关

}

}

class Woo{

public void t(Super obj){

System.out.println("Goo t(Super)");

obj.s();//调用对象的方法,Sub对象,打印Sub s()

}

public void t(Sub obj){

System.out.println("Goo t(Sub)");

obj.s();

}

}

class Super{

public void s(){

System.out.println("Super s()");

}

}

class Sub extends Super{

public void s(){

System.out.println("Sub s()");

}

}

更多推荐

java继承的内存分析

本文发布于:2024-02-10 22:26:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1677642.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!