What is the difference between C structures and Java classes?

前端 未结 4 559
臣服心动
臣服心动 2021-02-08 18:21

I\'m a newbie to Java, but somewhat familiar to C. I wanted to know -- what differences are there between C structures and Java objects and invoking their methods? Or are the

4条回答
  •  被撕碎了的回忆
    2021-02-08 19:10

    A Java class lets you define fields, like a C struct, but has the following additional features:

    • As you state in your question, you can add methods to a class which can operate on the data.
    • You can declare both fields and methods private (and a few other access settings), which means only other methods of the class can access them, not code from outside. (It wouldn't make sense to have this on structs, since there would be no way to access private fields -- this only makes sense when you allow methods).
    • Classes can inherit from other classes. Among other things, this lets you pass an object of type B where a type A was expected, as long as B inherits from A.

    There is another subtle difference. In C, structs are value types but in Java, classes are reference types. That means when you copy a struct in C (such as assigning to a variable or passing as an argument), it gets all of its fields copied, whereas in Java, when you copy a class object, it just copies the reference to the object (so if you modify its fields, you modify the original object as well, not just the copy).

    In C, you often use pointers to structs to emulate the reference behaviour of Java. In Java, you don't use pointers because class objects are already references.

提交回复
热议问题