Posts

Showing posts with the label constructor

Constructor in Java

Objects in Java are allocated on a system “heap” memory space. Unlike other languages, however, we needn’t manage that memory ourselves. Java takes care of memory allocation and deallocation for you. Java explicitly allocates storage for an object when you create it with the new operator. More importantly, objects are removed by garbage collection when they’re no longer referenced. Constructors Objects are allocated with the new operator using an object constructor. A constructor is a special method with the same name as its class and no return type. It’s called when a new class instance is created, which gives the class an opportunity to set up the object for use. Constructors, like other methods, can accept arguments and can be overloaded. they are not, however, inherited like other methods. There are two types of constructors: 1. Default constructor (no-arg constructor) A constructor that has no parameter is known as default constructor. If we don’t define a c...