Static Rules and How to Access a Static Method in Java

Static Rules and How to Access a Static Method in Java

Static Rules and How to Access a Static Method in Java

 

Static Rules and How to Access a Static Method in Java. In this article we will look into the Static Rule , and how we can access a Static Method without  using a Static Variable.

Refer the Table below for Static Rules.

No Static Rules
1 A Static Method cannot use a non Static Variable or Method directly
2 The Keyword This & Super cannot be used in Static Context

Refer the Code  below  to Learn How we can Access a Static Method

In this Code Example, I will create a Static Method , a static Variable and a non Static Variable as well

  1. As we are using the Scanner , to get the input data  from the User , thus we might need to import java.util.*;
  2. The Second Step is to declare a Static Variable call “addInput”
  3. Create the Add static Method i called it addNumber
  4. This Method will take in the Value from the user , add the number together and return the result to the User via aNumber
  5. Go back to the main , create 2 new Scanner object inputScan1 and InputScan2
  6. Create a print out statement to ask the User to input their first Number
  7. Save the First Input into the public static int addInput
  8. Create a print out statement to ask the User to input their second Number
  9. Create a new object or instance of class staticRules
  10. Call the addNumber()via the new instance called formulaer that you have created and pass the user second input into the addNumber()method
  11. Assign the result to int output
  12. Finally Print out the Result

 

package oop2;

import java.util.*;

public class staticRules {
	
	public static int addInput;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Scanner inputScan1= new Scanner(System.in);
		Scanner inputScan2= new Scanner(System.in);
		
		System.out.println("Please Key in your  first Input Number");
	     
		addInput =inputScan1.nextInt();

		System.out.println("Please Key in your  Second Input Number");
	     
		int addInput2 =inputScan2.nextInt();
		
		staticRules formulaer = new staticRules();
		
	         int output  = formulaer.addNumber(addInput2 );
	     
	 	System.out.println("Your First Input + Second Input equal= ." + output);

	}
	
	public static int addNumber(int aNumber){
		
	
		aNumber = aNumber + addInput;
		
		
		
		return aNumber;
		
		
	}

}



Well this Wrap up on what is Static Rules and How to Access a Static Method in Java.Check out how to integrate Static Keyword over here

If you have any problem you can always refer here plenty of resources.

Leave a Reply

Your email address will not be published. Required fields are marked *

9 + six =