Java Programming | Introduction to constructors

Introduction

This is a tutorial for introduction to constructors. The program is given below that uses constructor to create a object. The program is extendable. Go enjoy the program. Lets begin…………

Before you begin.Do this

  1. Create a separate java file for other class.
  2. Create a java file for main class.
  3. Import the created java class in main class file.

Program for constructors in java.

1. Create a class with constructor

//declare the package name if the class file is
package Myclasses;
 
//decalre class
public class Number {
 
    //variables
    private int a,b,sum;
 
    //a constructor
    public Number(int x,int y)
    {
        a=x;
        b=y;
    }
 
    //fucntions
    public void addthem()
    {
        sum = a+b;
    }
 
    public void print()
    {
        System.out.println("Sum = "+sum);
    }
}

Output

Enter 2 numbers:
1
2
Sum = 3

How it Works

  1. Objects of class are created by calling constructor.
  2. The sum function is called from main class.
  3. The print function is called from main class.

Extending it

The program can be extended by using the concept in any program.

  • Remember this is a basic part of java which can be used in any program….

Explanation.

Your class

  1. Create class.
  2. Import the Scanner.
  3. Declare the class as public
  4. Declare variables.
  5. Create a constructor.
  6. Create functions.

Main class

  1. Create other class
  2. Import your class.
  3. Declare the class as public.
  4. Add the void main function.
  5. Take inputs.
  6. Declare object and call constructor.
  7. Call functions.

At the end.

You learnt creating the Java program for Introduction to constructors . So now enjoy the program.

Please comment on the post and share it.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: