How to Create Class, Object, Method and Constructors.

How to Create Class and object in java.

Class 

First of all we declare one access specifier.this is not Mandatory.we have not declare any access specifier java Assume public access specifier automatically and then write class and space calssname and open and close curly brackets ( { } ).

Object 

Creating an Object In Java, the new keyword is used to create new objects. Declaration

− A variable declaration with a variable name with an object type. Instantiation

− The ‘new’ keyword is used to create the object. Initialization

− The ‘new’ keyword is followed by a call to a constructor.

Example of Class and Object:- 


public class alpha                // defining class
{
  int x=10;
 
  public static void main(String[] args) {
    alpha a1=new alpha();        //defining object(p1)
    System.out.println("value of X is"+p1.x);
  }
}


Output :-

value of X is:10

How to Create Method in java.

A method is a block of code which only runs when it is called.You can pass data, known as parameters, into a method.Methods are used to perform certain actions, and they are also known as functions.General form of method.

 type name(parameter-list){
 // body of method
 }

Type : Data return by method

Name : Name of the method

Parameter-list : Sequence of type and identifier pairs separated by commas. 

Example of Method :-

public class alpha
{
    void method1() //Method without parameter
    {
        System.out.println("This method is without parameter.");
    }
    void method2(int a) //Method with parameter
    {
        System.out.println("This method is with parameter.");
        System.out.println("Value of A is:"+a);
    }

    public static void main(String[] args) {
    alpha a1=new alpha();
    a1.method1();   //call without parameter method
    a1.method2(100);//call with parameter method
  }
}

Output :-

This method is without parameter.
This method is with parameter.
Value of A is:100

How to Create Constructors in java

It can be tedious to initialize all of the variable in a class each time an instance is created.Java allows objects to initialize themselves when they are created.This automatic initialization is performed through the use of Constructor.Constructor initializes an object immediately upon creation.

It has, Same name as the class in which it resides Syntax similar to a method No return type.

Example of Constructors :-

public class alpha{ 
    int a;
    alpha()//Create a class constructor for the alpha class
    {
       a=50;//assign value of a
    }
 public static void main(String[] args) {

     alpha p1=new alpha(); //Create an object of class alpha(This will call the constructor)
     System.out.println("value of A is:"+p1.a);
    }
}

Output :-

value of A is:50

I hope you understand this. If you interested more then subscribe our youtube channel named alphaprogrammer.

Thank You 🙂

Leave a Comment

Your email address will not be published.