Computer Science, asked by Tina11111, 1 year ago

write a java program using a constructor

Answers

Answered by 15121115anil
3
Constructors are special member functions whose task is to initialize the objects of its class. It is treated as a special member function because its name is the same as the class name. Java constructors are invoked when their objects are created.
Java allows objects to initialize themselves whenever they are created. This automatic initialization is performed by the use of a constructor.
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the object is created, and memory is allocated for the object.

It is a special type of method which is used to initialize the object.

Java compiler distinguish between a method and a constructor by its name and return type. In Java, a constructor has same name as that of the class, and doesn’t return any value.
he purpose of constructor is to initialize the object of a class while the purpose of a method is to perform a task by executing java code.
There are three types of constructors: Default, No-arg constructor and Parameterized.

1) Default constructor

If you do not implement any constructor in your class, Java compiler inserts a default constructor into your code on your behalf. This constructor is known as default constructor. You would not find it in your source code(the java file) as it would be inserted into the code during compilation and exists in .class file

2) no-arg constructor:

Constructor with no arguments is known as no-arg constructor. The signature is same as default constructor, however body can have any code unlike default constructor where the body of the constructor is empty.

Although you may see some people claim that that default and no-arg constructor is same but in fact they are not, even if you write public Demo() { }in your class Demo it cannot be called default constructor since you have written the code of it.


3) Parameterized constructor

Constructor with arguments(or you can say parameters) is known as Parameterized constructor.



A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method:



A constructor doesn’t have a return type.

The name of the constructor must be the same as the name of the class.

Unlike methods, constructors are not considered members of a class.

A constructor is called automatically when a new instance of an object is created


Hope, it may help you.✌️✌️




Tina11111: uuuu
Tina11111: ok
Tina11111: science
Tina11111: uuuu
Tina11111: ok
Similar questions