Java Class
A class is like a template (or blueprint) telling how objects of that class would look. For instance, the class called planet will contains the different planets as its objects.
Classes can be declared in the following way:
class MyClass { // field, constructor, and // method declarations }
Class declaration can also include Modifiers such as public,
private etc. Class body (within the curly brackets) contains
the objects and all the coding. A class can have fields,
constructors and methods and more..
Objects
Objects are instances of classes. When you create an object, that object will be of a certain class. Objects interact by invoking methods. Below is the syntax to create object:
new keyword:
The new keyword is used to allocate memory at runtime.
Above shows how the objects for the planet class can be created.
Methods
A method is a set of code which is referred to by name and can be called simply by utilizing the method’s name. Following is the Syntax of method:
Methods are groups of operations that carry out a certain function together.Methods are typically used when you need to group operations together, that you need to be able execute from several different places.
Advantage of Method
- Code Reusability
- Code Optimization
CONSTRUCTOR is a type of method which is used to initialize objects. Constructor will be invoked at the time of object creation. It constructs the values (provides data for the object) that is why it is known as constructor.
It looks like a method but the difference is Methods have return type but constructors don’t have any return type. And constructors must have the same name as the class name which does not require for methods.
- Name of the constructor must be same as the name of class
- They do not specify any return type not even void.
- Constructor initialize an object immediately after creation.