类对象关系如何工作?

时间:2018-08-04 22:18:56

标签: java oop

当我们创建一个类的实例时会发生什么?我的意思是,该类的每个字段和方法都将在该对象(具有分配的内存)中,还是在其内部不包含任何东西,而是对其类进行引用。 (第一个选项看起来很浪费内存。)

2 个答案:

答案 0 :(得分:5)

无论何时创建新对象,都会在堆空间(动态内存)中分配新的内存。该空间为类的单个实例所特有的所有内容保留。这意味着每个字段(实例字段,而不是静态字段)在内存中都有其自己的单独位置。

对于方法而言,情况有所不同,因为它们在类的所有实例中都是相同的,这意味着您将在内存中拥有一个方法,该方法将由类的每个实例引用。
如果您想知道某个方法的局部变量存储在哪里:它们存储在堆栈中,这意味着它们不会在该方法的调用之间共享。

此外,方法存储在“代码存储器”中,与实例字段分开。

答案 1 :(得分:1)

OOP(面向对象编程)的完整概念是能够通过“描述”对象来抽象现实。

要实现此目的,例如,我们可以声明一个对象属性。 您可以有一个对象Person,该人员具有不同的属性,例如姓名,年龄,地址。您还可以描述此人的不同动作,例如进食,洗澡等。其抽象如下:

class Person(){
     int age;
     String name;
     String address;

     void eating(){
         //describe the process of eating
     }

     void takeBath(){
          //describe the process of taking a bath
     }

}

这样做的全部目的是,之后您可以实例化一个Object Person,并且它将具有其所有属性。 您可以在另一个类中调用该对象并将其实例化,该调用将类似于:

Person person1 = new Person(); //here you are saying that you have a new variable of type person
person1.name = "Eduardo"; //You're saying that his name is Eduardo
person1.age= 28; //he is 28 years old
person1.eating(); //he's eating, I like to eat tho.

Person person2 = new Person(); //You are saying that there's another person
person2.name = "Maria"; //her name is Maria
person2.age = 31; //She's 31 years old
person2.takeBath(); She's taking a bath

如您所见,我不必再次声明类的方法或属性,只需创建一个新对象并开始设置属性(请注意声明和设置之间的区别,声明就是说有一个X类型的属性;设置为此属性赋予了一个值)。

OOP中还有另一个非常有用的属性,称为Heritage。假设我们要描述一个程序员;程序员是一个人,他可以做任何事,但他也可以编写代码,并且具有如下所示的首选语言:

class Programmer extends Person { // I'm declaring the class but also I'm saying it's a person, so it will have all the attributes and methods of the Person class.

       String preferredLanguage;  //I will only declare the new attribute that is preferred Language, name, age and address are set because it's a person



       void code(){
              //the process of making very awesome things
        }
}

然后我可以实例化另一个对象程序员

Programmer person3 = new Programmer();   //I called it person3 so you can understand it's only a variable, you can call it as you wish.
person3.name = "Berkay";  //Set the name without the need of declaring it in the method programmer, it's been inherit by the class Person
person3.code();//it can code!
person3.takeBath(); //A method of Person
person3.code(); //method of Programmer

在这一阶段,我想指出,具有Person属性的Programmer的含义并不相同。例如,尝试做到这一点将是一个错误:

person1.code(); //person1 is a Person and it doesn't have the code method.

PS:这些代码中有很多地方需要改进,离最佳实践还差得很远。我要做的只是给出一个清晰的示例,说明OOP的工作方式。我没有测试代码,这只是说明性的,可能包含错字