UNIT-I (Constructors & This Keyword)
UNIT-I (Constructors & This Keyword)
(PART-II)
JAVA ANATOMY
TOPICS:
JAVA Objects and References
Constructors
this Keyword
Arrays
Strings and Immutability
Buffer and Builder Classes
String Tokenizer
CONSTRUCTORS
Definition : Constructor is a Special Member Function
of a class that is used to create objects of that class.
It is a special type of method which is used to
initialize the object.
Syntax :
class MyClass
{
MyClass()
{
// Group of Statements
}
}
RULES FOR CREATING CONSTRUCTOR
There are Several rules defined for the constructor.
Those are :
Constructor name must be the same as its class name
A Constructor cannot have any return type not even
void.
A Java constructor cannot be abstract, static, final.
Constructors can not be Inherited.
TYPES OF CONSTRUCTORS
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
1.Default Constructor : constructor is
called "Default Constructor" when it
doesn't have any parameter.
If there is no constructor in a class,
Compiler automatically creates a
Default Constructor.
Eg-1:
O/P : 0 NULL
0 NULL
Eg-3: /*default constructor that displays the
addition of two numbers*/
A constructor is used to initialize the state of A method is used to expose the behavior of an
an object. object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default The method is not provided by the compiler in
constructor if you don't have any constructor any case.
in a class.
The constructor name must be same as the The method name may or may not be same
class name. as class name.
THIS KEYWORD
Definition : this Keyword is a reference
variable that refers to the current
object.
Usage of java this keyword :
1. this: to refer current class
instance variable :
The this keyword can be used to
refer current class instance variable.
If there is ambiguity between the
instance variables and parameters,
this keyword resolves the problem of
ambiguity.
Eg-1:Problem with out using this Keyword :
CONT…
O/P : 0 NULL 0.0