•
•
•
•
075.
There are several differences between a constructor and an
ordinary method. These are as follows:
A constructor has the
same name as the class name, an
ordinary method can have any name.
A constructor does not have a return type, not even void. A
method has a return type. If
a method does not return any
value, then the keyword void needs to be specified.
A constructor is automatically invoked when an object of the
class is created. A method needs to be invoked explicitly.
If a class
does not have a constructor, Java automatically
creates a default constructor.
If a class does not have a
method, Java does not automatically add a method.
Explain this keyword with a code sample.
Answer:
The this keyword is used to refer to the current object. It can be
used to reference a field or a
method corresponding to the
current object. The following code demonstrates this:
public class Book {
private String name;
private String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public void doSomething(Book book) {
}
public void doSomethingElse(Book book) {
this.doSomething(book);
}