12
Feb

Java Tutorial – 11 – Class


A class is a template used to create objects.
They are made up of members, the main two of which are fields and methods. Fields are
variables that hold the state of the object while the methods define what the object can
do. The class can also have a constructor. This
is a special kind of method used to initialize the object. It always has the same name as
the class and it doesn’t have a return type since it implicitly returns an new instance
of the class. To be accessible from another class it needs to be declared with the public
access modifier. When we create an new instance of this class
the constructor method is called, which here sets the fields to some default values. If
we want to we can add a parameter list to the constructor to make the fields initial
values depend on the parameters passed when creating the object. Inside of the constructor, as well as in other
methods belonging to the object, we can use a special keyword called this, which is a
reference to the current instance of the class. If we for example used the same name for the
parameters as for the fields, we could still access the fields by using this keyword, even
though they’re overshadowed by the local variables. To support different parameter lists we can
overload the constructor. If the class is now instantiated without any parameters the
fields will be assigned default values, with one parameter both fields will be set to that
value and for two parameters each of them will be assigned to a field. Trying to create
the object with more parameters than we’ve defined, or with incorrect data types, will
result in an error just as with any other method. The this keyword can also be used to call
one constructor from another. That way we don’t have to duplicate as much code. Note
that the keyword appears as a function call and that it must be on the first line in the
constructor. If there are fields in the class that needs
to be initialized to default values, such as in the first constructor here, we can just
as well initialize the fields at the same time as they’re declared. These default values
will be assigned before the constructor is called. It is possible to create a class even if there
are no constructors defined. This is because the compiler will then automatically create
a default constructor which takes no parameters when the program compiles.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

There are no comments yet

Why not be the first

Leave a Reply

Your email address will not be published. Required fields are marked *