Can we say Constructors are Methods in Java?

后端 未结 4 462
礼貌的吻别
礼貌的吻别 2021-01-29 15:57

As we know Java is an object oriented language. Everything is objects in Java. We also know that objects have something (instance variables / fields) and do something (methods).

4条回答
  •  长情又很酷
    2021-01-29 16:37

    Can we say Contructors are Methods in Java?

    If you're new to Java and trying to grasp the concept for the first time, you can think of constructors as factory methods. (Like in Python for instance where a constructor just a method called __init__.) You should however move on quickly and understand that there are many differences. To name a few:

    • A constructor does not have a return type.
    • It has special obligations when it comes to initializing final member variables (a method can't even assign to final members).
    • It's static in the sense that you can invoke it without a callee, but it's non-static in the sense that you have a this reference.
    • It's invoked with special keyword, new, and has a special bytecode, invokespecial, while instance methods are called by obj.method() which typically compiles to the invokevirtual bytecode.
    • It must invoke super constructors unless there's a no-arg constructor in super class.
    • They are never inherited and can not be overridden.

提交回复
热议问题