对象之特征或属性(Attribute)

对象之行为(Behavior)

软件中之对象时由数据(Data)和函数(Function)所组成.

类别与对象的关系: is a

重点关注对象创建时的内存模型:

堆,栈,代码区,全局数据区.

类的构造函数,如果没有构造函数那么系统会自动的分配一个不带参数的构造函数。如果类里面已经有一个带参数的构造函数,那么当创建对象的时候用不带参数的构造函数时将会发生错误,也就是说当定义了构造函数后,那么系统将不会再分配默认不带参数的构造函数.

父类和子类之间的继承关系是,子类继承了父类的属性,继承了父类方法的 使用权.

class Person{

int age;

String name;

Person\(\){

    this.age = 0;

    this.name = "";

}

void showInfo\(\){

    System.out.println\("age:"+age+",name:"+name\);

}

}

class Teacher extends Person{

int salary;

Teacher\(\){

    this.salary = 0;

}

void showInfo\(\){

    super.showInfo\(\);

    System.out.println\("salary:"+salary\);

}

}

public class Test7 {

public static void main\(String\[\] args\) {

    // TODO Auto-generated method stub

    Person p = new Teacher\(\);

    p.showInfo\(\);

}

}

上面中的Person p = new Teacher(); p.showInfo(); 是多态的一个应用。但是也可从内存的模型来理解这个,堆里面是Teacher的对象模型返回该内存的地址给栈里面的Perso p.也就是说p指向了堆空间里面的Teacher内存模型,所以p.showInfo()应该是调用Teacher里面的showInfo();

如果有如下的类结构那么构造方法的初始顺序是和C++一样的,对应的代码如下:

class SSS{

SSS\(\){

    System.out.println\("SSS"\);

}

}

class A{

SSS b = new SSS\(\);

A\(\){

    System.out.println\("A"\);

}

}

class B extends A{

B\(\){

    System.out.println\("B"\);

}

}

class C{

C\(\){

    System.out.println\("C"\);

}

}

class D extends C{

SSS b = new SSS\(\);

D\(\){

    System.out.println\("D"\);

}

}

public class Test8 {

public static void main\(String\[\] args\) {

    // TODO Auto-generated method stub

    B b = new B\(\);

    System.out.println\("================"\);

    D d = new D\(\);

}

}

在C语言中里面struct结构实现简单的"对象",当然没有继承/多态的性质.

struct student{

int name; char name\[10\];

void getName();

void setName();

void \(\*showInfo\)\(\);//用来函数指针来实现定制化,也可以说是C++中的晚绑定.

};

results matching ""

    No results matching ""