Java Programming | Introduction to class

Introduction

This is a tutorial for introduction to class in java. The program is given below that uses class to add two numbers. 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 using class in java.

1.Create add.java file

//declare the package name if the class file is
//created in other package.
package Myclasses;
 
//import scanner
import java.util.Scanner;
 
//declare class
public class add {
 
    //declare variables.
    private int a,b,sum;
 
    //functions should be public if needed to access from other class
    public void getdata()
    {
        //print message to enter numbers
        System.out.println("Enter 2 Numbers:");
        //Take input
        Scanner input = new Scanner(System.in);
        a = input.nextInt();
        b = input.nextInt();
    }
 
    public void sum()
    {
        sum = a+b;
    }
 
    public void print()
    {
        System.out.println("Sum = "+sum);
    }
}

2.Create ClassIntro.java (run ClassIntro file)

//import our class
import Myclasses.add;
 
// the name of our class its public
public class ClassIntro {
    //void main
        public static void main (String[] args)
        {
            //declare class
            add myclass = new add();
            //call functions
            myclass.getdata();
            myclass.sum();
            myclass.print();
        }
}

Output

Enter 2 Numbers:
1
3
Sum = 4

How it Works

  1. First the class is created.
  2. The getdata function is called from main class.
  3. The sum function is called from main class.
  4. The print function is called from main class.

Extending it

The program can be extended by using the concept in any program. Like for ex. you can create a same program for subtraction, multiplication,division,etc. Go ahead extend it……

  • 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 variable.
  5. 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. Declare class.
  6. Call functions.

At the end.

You learnt creating the Java program for Introduction to class . 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: