Classes are the basic building block of every java application. Class stores related data and also defines the methods to work on that data. Every program needs one class with a main method. This class is the entry point for the program. The code in the main method executes first when the program starts.
Let’s start with a very simple example:
The static fields and methods of a class can be called by another program without creating an instance of the class.
The public static void keywords conveys the following meaning to the Java interpreter:
public – Java Interpreter can call the program’s main method to start the program.
static – instance of the class need not be created to call the main method
void – the main method does not return data to the Java interpreter (void) when it ends.
the main calls the System.out.println method to display the value of i. The class Java.lang.System , has a static field out of type PrintStream that is used to invoke the println method.
A program must create an instance of a class to access its non-static fields and methods.
To illustrate this let’s write some simple code:
The class only describes the data and behavior. An instance of a class is an executable copy of the class. a class instance is needed to acquire and work on data.
Advantages of Using a class
- Use class to group related fields and methods.
- Use class to accelerate development by reducing redundant code entry, testing and bug fixing.
- Using a well-tested class or extending it will reduce, if not eliminate, the possibility of bugs propagating into the code.
- Using classes simplifies the relationships of interrelated data.
Inheritance provides a way in object oriented programming to define a new classes using predefined classes. The new class is known as derived class and the predefined class is referred as a base class. Inheritance helps in code reuse little or no modification. Below is the example of Inheritance in Java:
In the example above MyClass derived from the base class MyBaseClass and it inherits the properties and behavior of MyBaseClass, this demonstrates the reuse of the existing code.
Disadvantage of Inheritance:
- Inheritance locks your classes into a particular inheritance hierarchy as Java doesn’t supports multiple inheritance
Interfaces form a contract between the class and the outside world. An interface is a group of related methods with empty bodies. If a class implements an interface, all methods defined by that interface must be defined in the class.
Here class SayGoodMorning implements the interface Printable.
When to use interface:
- Design an interface when something in the design is going to change frequently
- You should generally favor interfaces over inheritance