开发者

class and method in java

i m jst confused that which of the two exists in the memo开发者_高级运维ry a class or the object?


The object.

At some extent, the class too, but I think what you mean is to clarify which one is the one holding the data.

For instance:

This is the class:

class Employee {
    String name;
}

And instance object would be:

Employee e = new Employee();
e.name = "himangi";

Employee other = new Employee();
other.name = "John";

There you have two objects, e and other they do exist in memory.

What makes it a little confuse is that Java stored the class definition as an object too, so in runtime you can have a the class object that represent the Employee class.

 Class employeeClass = Employee.class;
 System.out.println( employeeClass.getName() );

But then again, what exist in memory is the object.


The class is the blueprint for the object.

The class defines the methods and properties that an object will support / use.

The object is an instance of the blueprint.

Every time you create an object it will be held in memory,

i.e. 10 objects = 10 memory stored instances

A class is stored in memory so that the runtime environment can "lookup" the class definition / blueprint and create a new instance for you.

The difference here is that only one definition of the class would be stored in memory, regardless of the number of objects you create.

1 Class definition can have many object instances (unless the class is marked as static in which case there is 1 class definition and 1 instance.).

The same is true for most compiled languages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜