Classes and Constructors

Listen to this article

As already stated, Classes contain the blueprint for an Object. Each Class has variables and methods.

One important point before we start exploring more about classes:

The main() method is the stepping point for a Java compiler. The Java compiler looks for the main() method and starts its execution from there.

First let us get used to a simple Java program that makes use of methods and variables.

It may look mind boggling at first, but it is a simple program that employs methods and variables. This program takes two inputs from the user. One method (‘add’) adds the two inputs and the other method(‘sub’) subtracts the two inputs and returns the result.

The results are printed out in the ‘main’ method.

 

You can interactively try this program by pressing ‘Interactive’ button and then pressing ‘Execute’ button.

You will be prompted to enter the first number and then the second number following which the results will be printed out!

Note: Jdoodle is a bit slow…so, you may to wait after typing each input…

More about Classes:

  1. A Java program can have any number of classes in it but there can be only one public class.
  2. When there are several classes in a program they are also called as ‘Nested Classes’,
  3. The different types of Nested Classes are
  • Inner Classes
  • Static Nested Classes
  • Local classes
  • Anonymous inner classes

Inner classes can be declared like this:

class first{
    // some methods here
    //some variables here
   
    class second{

}
}

‘second’ is the inner class here. It has access to all of the methods and variables of the outer class namely, class ‘first’.

An instance of inner class ‘second’ can only exist as an ‘instance‘ of the outer class. This can be done as follows:

first A=new first();  //creating an instance of the outerclass 
first.second= A.new second();// creating an instance of inner class

Note: Being an instance of means creating an ‘Object’ of a Class.

Hence, instantiation is the process of creating an Object with the ‘new’ keyword

Constructors:

Once an Object is ‘instantiated’, the constructor of the class is called if there is one. Here are a few salient points about ‘Constructors’.

Constructors are methods that are used to initialize objects.

They do not have a return type.

They have the same name as the class

A class can have any number of constructors

Here is an example of a Constructor:

 

This program just prints the message ‘Constr’ by means of the constructor.

We will be seeing more about Constructors as our Java series unfolds! Stay tight and stay tuned! 🙂

I’m participating in #BlogchatterA2Z by Blogchatter 

(Visited 85 times, 1 visits today)

Related Posts

5 thoughts on “Classes and Constructors

Leave a Reply