chevron_left
399 points
8 4 3

How to reference a non static method in java

  • Class is a template and when we create object instance variables gets memory.
  • If we create two objects variables get memory in two objects. So instance variables gets memory whenever object is created.
  • When we create variables as static , memory will not be created in objects because static means class level and it belongs to class not object but we can access static variables and static methods from objects.
  • In our scenario calling a non static method from static method in java.
  • If we are calling a non static method then we need to use object so that it will call corresponding object non static method.
  • Non static methods will be executed or called by using object so whenever we want to call a non static method from static method we need to create an instance and call that method.
  • If we are calling non static method directly from a static method without creating object then compiler throws an error. 

 

 

​
import java.util.Scanner;
public class StudentMarks {
   Scanner scan1 = new Scanner(System.in);
   private double math;
   private double science;
   private double english;
   public StudentMarks(double math, double science, double english) {
      this.math = math;
      this.science = science;
      this.english = english;
   }
   public static boolean wasPromroted(StudentMarks marks) {
      if(math>=85 && science>=75 && english>=65) {
         return true;
      }
      return false;
   }
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your math score: ");
      double math = sc.nextDouble();
      System.out.println("Enter your science score: ");
      double science = sc.nextDouble();
      System.out.println("Enter your english score: ");
      double english = sc.nextDouble();
      StudentMarks marks = new StudentMarks(math, science, english);
      boolean bool = wasPromroted(marks);
      if(bool) {
         System.out.println("Congratulations you've got promoted");
      } else {
         System.out.println("Sorry try again");
      }
   }
}

​

 

More Posts

Cannot make a static reference to the non-static method in java Tania - Sep 7
Cannot make a static reference to the non- static method in java Sitara khan - Sep 2
How to call non static method from static method in java? Hafsa_Rao - Jun 30
Can we declare abstract static method amna - Jul 28
Why we cannot make a static reference to the non-static method? mhfaisal - May 14
Difference between class method and static method in python Tania - Aug 9
Cannot make a static reference to the non-static method java SharadMagar450 - Aug 5
How to access a static variable in java offonime - Jul 4
How to make a tostring method in java amna - Jul 28
The static method should be accessed in a static way Hafsa_Rao - Jul 17