Are Java classes objects?

2019-01-26 10:17发布

I've read before that Java classes are instances of the class Class. But now, my computer science teacher says that Java classes are not objects.

Which is true?

标签: java oop
4条回答
我想做一个坏孩纸
2楼-- · 2019-01-26 10:41

Every Java class, even java.lang.Class descends from java.lang.Object.

EDIT:

The wording is a bit ambiguous. The instances of Java classes are definitely objects. Classes by themselves, cannot be really considered objects, well because nothing exists in memory except for the class "blueprint".

查看更多
Lonely孤独者°
3楼-- · 2019-01-26 10:42

The class (your code, or even the compiled code in your .class files) are not objects. You don't have an object until you instantiate that class.

For example, Java.lang.String is a class. String s = new String("Hello world"); defines an object of type String. That may be the distinction your professor is making.

查看更多
够拽才男人
4楼-- · 2019-01-26 10:43

Java classes are not objects, they're an abstraction.

However, each Java class has a corresponding instance of the java.lang.Class class that represents it. That representation is an object. But you shouldn't mistake the representation for the actual thing.

The relationship is somewhat similar to that between music and sheet music. Although the written notation represents music, it is not itself the music.

The difference rarely matters in practice though, so long as you know what you can and cannot do with java.lang.Class objects.

查看更多
Deceive 欺骗
5楼-- · 2019-01-26 10:48

A Java class is not an object.

However, every Java class has an instance of the Class class describing it.
Those instances are objects.

查看更多
登录 后发表回答