Professional Documents
Culture Documents
1
Constructor and Classes
Constructors
If you ever wonder what constructors and classes are used for, then think
about it this way – social media, and/or other sites that require an account,
use constructors and classes to process and serialize (encrypt) your data
before it goes to a data base.
Oh, and some more for you game savvy kids, these are used for item
generation, character classes and saves in your games to name a few.
Constructors
A Constructor in Java is a special method used to initialize objects. Upon
creation of an object, a constructor is invoked. It provides an object
with its default values constructing it, thus the name constructor.
Constructors have two rules you must follow as of now, but it’s not
compulsory if you’re a master magician. . . I mean an exceptional
programmer.
These rules are:
1. A constructor should have the same name as your class; and
2. A constructor cannot have an explicit return (return itself) type.
Course Module
Or
<class_name>( param, param . . . ){ }
Overloading Constructors
What is overloading and why do you need to overload? First of all, this is not
the type of overloading that causes accidents, e.g. an overloaded jeepney that
crashed into a light post.
Not that kind of stuff, this is the overloading that you need to get things done.
Course Module
Classes
Nested Classes
Remember if-else and loop statements? Loopception and switchception?
Declaring a loop inside a loop inside a loop – nested loops?
You can also do that with classes. In Java, it is possible to define a class
within another class.
Why should you implement nested classes?
1. Nested classes provide a logical way to group classes that are used in
one place. If you have a class which is only useful to one class, then it is
logical that you embed it inside that class to group them together.
2. Nested classes increase encapsulation. You can hide the nested class
inside the outer class and keep it private.
3. Nested classes make the code more readable and maintainable. It is
easier to read if a particular class is close to where it is used (top level
class).
The syntax in defining nested classes is:
class OuterClass {
...
class NestedClass {
...
}
}
Course Module
Abstract Classes
This type of class encloses one or more abstract methods. Abstract methods
are methods with no implementation or body that require sub-classes to be
responsible for implementations.
Figure 4. Abstraction
References
Oracle. Java™ Platform Standard Ed. 7. Retrieved from:
https://docs.oracle.com/javase/tutorial/java/
Course Module