Java error cannot referenced static context

«non static method cannot be referenced from a static context» JPA Java

I’m getting the «non static method cannot be referenced from a static context» error from this line: createStudent(«stu00001», new Date(631152000000)), «m», «WB», new Type_Name(«Bob», «», «Smith»)); How do you form ‘Date’ properly? I’ve had a look on the API’s and tried different things but I still get an error for date.

package grade_db; import bean.Student; import bean.Type_Name; import bean.University; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * * @author Sam */ public class Main < EntityManager em; EntityManagerFactory emf; /** * @param args the command line arguments */ public static void main(String[] args) < // TODO code application logic here EntityManagerFactory emf = Persistence.createEntityManagerFactory("db/grades.odb"); EntityManager em; em = emf.createEntityManager(); createStudent("stu00001", new Date(631152000000)), "m", "WB", new Type_Name("Bob", "", "Smith")); em.close(); emf.close(); >public Student createStudent(String student_id, Date dob, String gender, String nationality, Type_Name name) < Student stu = new Student(); stu.setDob(dob); stu.setGender(gender); stu.setName(name); stu.setNationality(nationality); stu.setCampus_id("cam00001"); stu.setCourse_id(null); stu.setStudent_id(student_id); em.persist(stu); return stu; >> 

3 Answers 3

The problem is that you’re trying to call the instance method createStudent() from a static context in main() . If you change your createStudent() method to be static, you should be good to go:

public static Student createStudent(String student_id, Date dob, String gender, String nationality, Type_Name name) < // . And so on >

EDIT: OP pointed out that this change alone gives him another error when accessing the variables em and emf . To fix that, you’d need to make those variables static , too:

static EntityManager em; static EntityManagerFactory emf; 

At that point, everything in your class is static. Assuming this is a simple one-off or example — which I’m comfortable assuming since the class is called Main — making everything static is just fine. In all, the code would look like this:

package grade_db; import bean.Student; import bean.Type_Name; import bean.University; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * * @author Sam */ public class Main < static EntityManager em; static EntityManagerFactory emf; /** * @param args the command line arguments */ public static void main(String[] args) < // TODO code application logic here EntityManagerFactory emf = Persistence.createEntityManagerFactory("db/grades.odb"); EntityManager em; em = emf.createEntityManager(); createStudent("stu00001", new Date(631152000000)), "m", "WB", new Type_Name("Bob", "", "Smith")); em.close(); emf.close(); >public static Student createStudent(String student_id, Date dob, String gender, String nationality, Type_Name name) < Student stu = new Student(); stu.setDob(dob); stu.setGender(gender); stu.setName(name); stu.setNationality(nationality); stu.setCampus_id("cam00001"); stu.setCourse_id(null); stu.setStudent_id(student_id); em.persist(stu); return stu; >> 

Источник

Читайте также:  Date in javascript mozilla

How to Resolve The Non-static Variable/Method X Cannot be Referenced from a Static Context Error in Java

How to Resolve The Non-static Variable/Method X Cannot be Referenced from a Static Context Error in Java

The static keyword in Java is a modifier that makes a member of a class independent of the instances of that class. In other words, the static modifier is used to define variables and methods related to the class as a whole, rather than to an instance (object) of the class. Hence, static variables are often called class variables, while static methods are commonly referred to as class methods. Class variables and methods are stored in fixed locations in memory and are accessed without a reference to an object, directly through the class name itself [1].

A common use for static methods is to access static variables. However, not all combinations of instance and class variables and methods are allowed. Namely, static methods can only use static variables and call static methods—they cannot access instance variables or methods directly, without an object reference. This is because instance variables and methods are always tied to a specific instance, i.e., object of their class.

Due to their instance-less nature, static variables and methods are sometimes used to construct stateless utility classes [2].

Non-static Variable X Cannot be Referenced from a Static Context & Non-static Method X Cannot be Referenced from a Static Context

A static variable is initialized once, when its class is loaded into memory, and its value is shared among all instances of that class. On the other hand, a non-static variable is initialized every time a new instance of its class is created, and as such there can be multiple copies of it in memory, each with a different value. Consequently, attempting to access a non-static variable from a static context (a static method or block) without a class instance creates ambiguity—every instantiated object has its own variable, so the compiler is unable to tell which value is being referenced. And if no class instance is created, the non-static variable is never initialized and there is no value to reference. For the same reasons, a non-static method cannot be referenced from a static context, either, as the compiler cannot tell which particular object the non-static member belongs to.

To prevent this conundrum when accessing instance variables and methods from a static context, the Java compiler raises the non-static variable X cannot be referenced from a static context, or the non-static method X cannot be referenced from a static context error, respectively. To rectify this problem, there are two possible solutions:

  • refer to the non-static member through a class instance, or
  • declare the non-static member static.

Examples

Non-static Variable X Cannot be Referenced from a Static Context

The code example in Fig. 1(a) shows how attempting to increment and print the value of the non-static variable count from the static main method results in the non-static variable count cannot be referenced from a static context error. The Java compiler flags both attempts to reference the instance variable without an actual class instance and points to their exact location in the source code.

Creating a local class instance in the main method and accessing the count variable through this object resolves this issue (Fig. 1(b)), as it unambiguously links the variable to a specific object. In scenarios where the variable in question doesn’t need to hold data specific to a class instance, but can either be shared among all class instances or used independently of any, adding the static modifier to it makes it accessible from a static context, effectively resolving the error, as shown in Fig. 1(c).

package rollbar; public class StaticContextVariable < private int count = 0; public static void main(String. args) < count++; System.out.println(count); >>
StaticContextVariable.java:8: error: non-static variable count cannot be referenced from a static context count++; ^ StaticContextVariable.java:9: error: non-static variable count cannot be referenced from a static context System.out.println(count); ^ 2 errors 
1 2 3 4 5 6 7 8 9 10 11 12
package rollbar; public class StaticContextVariable < private int count = 0; public static void main(String. args) < var classInstance = new StaticContextVariable(); classInstance.count++; System.out.println(classInstance.count); >>

Источник

Java error cannot referenced static context

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Ошибка “non-static variable this cannot be referenced from a static context” при попытке создания объекта вложенного класса

Люди, спасите пожалуйста. Написала класс, хочу создать объект, а выдается ошибка “non-static variable this cannot be referenced from a static context”. Звездочками выделила проблемные моменты:

package com.company; import java.math.BigInteger; import java.util.BitSet; import java.util.Random; public class Main < // ** public static void main(String[] args) < BitSet d = new BitSet(128); BitSet d1 = new BitSet(128); Bits bits = new Bits(128, d, d1 ); >// ** class Bits < private BitSet bit1, bit2; //поля экземпляра private int size; private Random random; // ** public Bits (int size, BitSet b1, BitSet b2) //конструктор < bit1 = b1; bit2 = b2; >// ** > 

1 ответ 1

non-static variable this cannot be referenced from a static context

Другими словами: вы используете нестатическую переменную this внутри статического контекста метода main .

Вы можете возразить, что явно Вы данную переменную нигде не указывали.
И да, в Вашем коде её нет.

Данную переменную Вы использовали неявно, когда создавали объект Bits .
Фактически он ругается на использование this.Bits .

this.Bits — именно так, потому что данный вложенный класс находится в нестатическом контексте и принадлежит ему.

Вложенные классы подчиняются тем же правилам, что и другие ресурсы класса.
В Вашем случае, например, объект Bits должен иметь доступ к контексту объекта Main .
Но его(экземпляра объекта Main ) нет, как и нет его контекста, а следовательно и нет доступа к классу Bits .
Именно поэтому и возникает ошибка.

  1. Объявите вложенный класс в статическом контексте. Для этого достаточно просто добавить модификатор static перед объявлением вложенного класса

Ну и добавлю еще третий вариант:

Источник

non-static variable arr cannot be referenced from a static context [duplicate]

I’ve read the Oracle documents regarding scope and controlling access yet it just isn’t sticking, so I’m assuming that my issue comes from my failure to understand. Anyways Here’s my code. I’m trying to access the unique Player objects created in an array, and change their unique variables like their balances, using methods from the Player class. Any solutions and ESPECIALLY explanations are welcome!

public class Player < private int currentBal; private String myName; private int rollOne; private int rollTwo; private int rollTotal; private int doublesCount; private int currentPosition; private int currentDoubles; private int move; private int moveMult; private int newBal; private boolean rollAgain; private boolean inJail; public Player(String userName, int changeInMoney) < myName = userName; currentBal -= changeBalance(changeInMoney); >public int changeBalance(int changeInMoney) public int viewBalance()
public class PlayerArray < Scanner scan = new Scanner(System.in); private int numbHuman; private Player[] arr; private String[] userName; private int startingMoney; public PlayerArray() < Scanner scan = new Scanner(System.in); System.out.println("There will be 4 players, how many do you wish to be human? 0> <4"); numbHuman = scan.nextInt(); while (numbHuman < 1 || numbHuman >4) < System.out.println("Invalid entry, try again."); numbHuman = scan.nextInt(); >arr = new Player[numbHuman]; userName = new String[numbHuman]; startingMoney = 1500; for(int i = 0; i < arr.length; i++) < System.out.println("Player " + (i + 1) + ", Please enter your first name:"); userName[i] = scan.next(); arr[i] = new Player(userName[i],startingMoney); >> public Player[] getPlayerArray() < int charge = 500; arr[0].changeBalance(charge); System.out.println(arr[0].viewBalance()); //look here as example return arr; >> 

this is my player class, minus some methods I can’t use till later. Bellow is my main method to call it,

import java.util.Scanner; import java.util.Random; public class Launcher < private Planet myTest; private PlanetInfo myPlanetInfo; private static Player[] arr; public static void main(String[] args) < Launcher testLauncher = new Launcher(); PlayerArray myArray = new PlayerArray(); Pay myCharge = new Pay(); // continue work on charges myArray.getPlayerArray(); //STILL TRYING TO GET BELLOW LINE TO WORK LAST NIGHT. int testBal = arr[0].viewBalance(); //ERROR HERE System.out.println("player 1's balance: " + testBal); >> 

For starters, next time you get an error message, try copypasting the entire error message in Google (after stripping out program-specific class/method/variable names). You’d be surprised about the results.

@Shamikul_Amin Probably should add my PlayerArray class so you can see what exactly is going on. I want the user to select how large the array is and how many objects it’ll make and hold.

4 Answers 4

Your main method is a static method. It actually exists before any object is created from your class, and thus cannot access instance variables and methods directly. You cannot access non static methods or variables from the same class unless you create an object for the class, i.e Launcher launcher = new Launcher(); .

In this case, your player array arr is not static. You either need to make this static or create a Launcher object and access the variable from there. In the latter case, you will need to make the arr array public.

The first option requires you to change your player array declaration to private static Player arr; .

The second requires you to change the access of the arr array to public and access it like so: launcher.arr .

Regarding your second error, you need to either do this: arr = myArray.getPlayerArray(); or just access the array directly like this: myArray.getPlayerArray()[0] (for the first item in that array).

Источник

Оцените статью