I can't get this Java code to work. I have read multiple examples, but none explains why the code doesn't work.
The code:
class Main {
public static void main(String[] args) {
class UserInfo {
public String Name = "Example Name";
public int Age = 13;
static int GetAge() {
return (Age);
}
}
UserInfo.GetAge();
}
}
Please note I am very new to Java.
You cannot call non-static method from static context without creating new UserInfo object. You need to create new UserInfo object
class Main {
public static void main(String[] args) {
class UserInfo {
public String Name = "Example Name";
public int Age = 13;
int GetAge() {
return (Age);
}
}
UserInfo userInfo = new UserInfo();
userInfo.GetAge();
}
}
You cannot call a non-static method from a static context. I have moved the class outside of the method and made it static.
Try the code below:
class Main {
public static void main(String[] args) {
System.out.println(UserInfo.GetAge());
}
static class UserInfo {
public String Name = "Example Name";
static int Age = 13;
static int GetAge() {
return (Age);
}
}
}
However, if you want a dynamic class in where you can define the name and age, use this code below:
class Main {
public static void main(String[] args) {
UserInfo userInfo = new UserInfo("John", 13);
System.out.println(String.format("Name: %s Age: %s", userInfo.getName(), userInfo.getAge()));
}
static class UserInfo {
String name;
int age;
UserInfo(String name, int age){
this.name = name;
this.age = age;
}
int getAge() {
return age;
}
String getName() {
return name;
}
}
}
Error 1:
age is an instance variable. You can not use it inside the static method GetAge(), so either make Age static or make a getAge instance...
static int GetAge() {
return (Age);
}
Error 2: you can not access an instance variable GetAge() using a class name reference. To correct it, you have to create an object and use this reference to access it.
UserInfo.GetAge(); // Does not compile
Instead use:
UserInfo userInfo = new UserInfo();
userInfo.GetAge();
Generally, instance variables can not be used inside static methods and you can not use class reference to access an instance member in Java.
First of all, you cannot call a non-static method from a static context. You should need to move the inner class outside from the main method and make it static.
Try this one:
public class Main {
public static void main(String[] args) {
System.out.println(UserInfo.GetAge());
}
static class UserInfo {
public String Name = "Example Name";
public static int Age = 13;
static int GetAge() {
return (Age);
}
}
}
Related
This question already has answers here:
Can we instantiate an abstract class?
(16 answers)
Closed 3 years ago.
How to create object for abstract class with out creating sub class object and referring its own object
For example :
public class abstract student{
private int sno;
private String sname;
}
public class Test{
public static void main(String[] rs )
{
Student s= new Student();// it is not working
}
}
Without creating sub class or implementation class I need solution
The idea of an abstract class is to explicitly prevent it being instantiated. That's really the point of it being abstract.
However you can subclass it anonymously:
Student student = new Student() { };
This creates a new, nameless, extension of Student.
<code>
package com.glen;
public abstract class student {
private final int sno;
private final String sname;
public int getSno() {
return sno;
}
public String getSname() {
return sname;
}
public student(int sno, String sname) {
super();
this.sno = sno;
this.sname = sname;
}
#Override
public String toString() {
return "student [sno=" + sno + ", sname=" + sname + "]";
}
}
-----------------------
package com.glen;
public class Test {
public static void main(String[] args) {
student s=new student(10,"raja") {};
System.out.println(s);
}
}
</code>
I am trying to use a getter to retrieve some variables that the user will input into a GUI, however it gives me an "non-static method cannot be referenced from a static context" error. I have tried making my getters and setters static and that did not work. I am not sure where to go from there. Here is my code:
Main:
public class creditInfoSystem {
String name = infoGUI.getName();
public static void main(String[] args) {
new infoGUI();
}
public void getData() {
}
}
Getters+Setters From GUI Class:
public void setName(String newName){
name = newName;
}
public String getName(){
return name;
}
public void setCustNum(double newCustNum){
custNum = newCustNum;
}
public double getCustNum(){
return custNum;
}
public void setCreditLimit(double newCreditLimit){
creditLimit = newCreditLimit;
}
public double getCreditLimit(){
return creditLimit;
}
public void setPrevBalance(double newPrevBalance){
prevBalance = newPrevBalance;
}
public double getPrevBalance(){
return prevBalance;
}
public void setCurrentPurchases(double newCurrentPurchases){
currentPurchases = newCurrentPurchases;
}
public double getCurrentPurchases(){
return currentPurchases;
}
public void setPayments(double newPayments){
payments = newPayments;
}
public double getPayments(){
return payments;
}
public void setCreditsReturns(double newCreditsReturns){
creditsReturns = newCreditsReturns;
}
public double getCreditsReturns(){
return creditsReturns;
}
public void setLateFees(double newLateFees){
lateFees = newLateFees;
}
public double getLateFees(){
return lateFees;
}
I can provide more parts of the code if needed.
The problem is that the creditInfoSystem class has no idea which infoGUI class you are referring to. Try and make infoGUI a parameter of creditInfoSystem and retrieve the data from there.
public class creditInfoSystem {
private InfoGUI infoGUI;
public creditInfoSystem(InfoGUI gui){
infoGUI = gui;
name = infoGUI.getName();
}
public static void main(String[] args) {
InfoGUI infoGUI = new infoGUI();
CreditInfoSystem sys = new creditInfoSystem(infoGUI);
}
}
If you are building a swing/FX GUI:
One problem I can predict is knowing when the name in the GUI is actually set. You should maybe consider making the GUI the main program where CreditInfoSystem is an attribute of the GUI. Then when a button is clicked or some other action, the input from the GUI is taken and passed to the CreditInfoSystem.
First of all, rename your classs InfoGUI and CreditInfoSystem, starting with an upper case, it is a Java convention.
Then, when you do InfoGUI.getName() you are trying to access a class method, which would have to be static. What you want to do is create an instance of InfoGUI and access it's instance method.
Also your name variable should be static because you use it in a static method, ie public static void main
public class CreditInfoSystem {
private static String name;
public static void main(String[] args) {
// Create an instance of your InfoGUI class
InfoGUI infoGuiInstance = new InfoGUI();
// Call the getter on the instance you just created
name = infoGuiInstance.getName();
}
}
And the renamed InfoGUI class:
class InfoGUI {
String name;
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
}
how do I call a void method from another class to a new class with main?
I have two classes, but I don't see the error I am making.
public class Person {
private int age;
private String name;
public Person(int a, String n) {
a = age;
n = name;
}
public void printInfo() {
System.out.println(age + name);
}
//
public class Main {
public static void main(String[] args) {
Person obj1 = new Person(22, "Dan");
obj1.printInfo();
}
}
EDIT: Move the main method to a different class and done.
TestPerson.java
public class TestPerson {
public static void main(String[] args) {
Person obj1 = new Person(22, "Dan");
obj1.printInfo();
}
}
You have few mistakes in your code. It should be like as follows :
public class Person {
private int age;
private String name;
//Your constructor was wrong
public Person(int a, String n) {
age = a;
name = n;
}
public void printInfo() {
System.out.println(age + name);
}
}
I have super class called pojo. I have a subclass called ExtendPojo.
pojo.java
package com.java.pojo;
public class pojo {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
public String toString() {
return "pojo [name=" + name + ", age=" + age + ", number=" + number + "]";
}
private String name;
private int age;
private long number;
}
ExtendPojo.java
package com.java.pojo;
public class ExtendPojo extends pojo{
public static void main(String[] args) {
pojo obj = new pojo();
obj.setName("santhosh");
ExtendPojo exObj = new ExtendPojo();
exObj.setName("mahesh");//It is not overriding
System.out.println(obj.getName());//it prints santhosh.
}
public void setName(String name){
super.setName(name);
}
}
You are creating two independent objects.
First you create an object and name it santhosh. This object is referenced by the obj variable.
pojo obj = new pojo();
obj.setName("santhosh");
Then you create a second object, which is referenced by the exObj variable.
ExtendPojo exObj = new ExtendPojo();
It doesn't have a name yet, since it's a new object and you haven't assigned the name. You then give it a name.
exObj.setName("mahesh");//It is not overriding
Now you print the name of the first object, which hasn't changed.
System.out.println(obj.getName());//it prints santhosh.
The code is doing exactly what you asked it to do.
If you intended the two variables to reference the same object, you'd do this:
ExtendPojo exObj = new ExtendPojo();
pojo obj = exObj ;//Same object, new variable, different type
obj.setName("santhosh");
exObj.setName("mahesh");//It is working now
System.out.println(obj.getName());//it prints mahesh.
I have gone through the Inheritance and method overriding concepts and clarified my doubts :)
public class ExtendPojo extends Pojo{
public static void main(String[] args) {
Pojo obj = new Pojo();
obj.setName("santhosh");
Pojo obj1 = new ExtendPojo();
obj1.setName("mahesh");//It is overriding now
System.out.println(obj1.getName());//it prints mahesh.
}
}
I need to write some code which is as follows:
public class Person {
public static final String NAME;
public Person(String NAME) {
this.NAME = NAME;
}
}
public class Player extends Person {
public Peter(String name) {
super(name);
}
}
It's basically, I want the Player class to have a static final field called NAME, that is being initialized somewhere else, without manually writing in every class public static final String NAME = "Peter".
Is it possible?
As it has been said in the comments, you have poorly declared your NAME variable. In actuality, you don't want it to be static (although you can keep the final modifier, if you want). Your code should, instead, be something along the lines of:
public class Person {
public final String name;
public Person(String name) {
this.name = name;
}
}
public class Player extends Person {
public Player(String name) {
super(name);
}
}
Every person should have their own name; you don't want all objects to be sharing one NAME field
I do not know if I fully understand your question, but I think you have a few mistakes in your code. Like declare name of person as static variable, because static variables are often used as variables for the entire class, and if you changed the name, would change the name to the entire class, not for one instance. Also final is wrong, because you cannot set final variable.
I would do something like this:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return String.format("Person: %s", this.getName());
}
}
public class Player extends Person{
public Player(String name) {
super(name);
}
public String toString(){
return String.format("Player: %s", this.getName());
}
}
public class Match {
private Player player_one;
private Player player_two;
public Match(Player player_one, Player player_two) {
this.player_one = player_one;
this.player_two = player_two;
}
public Player getPlayer_one() {
return player_one;
}
public void setPlayer_one(Player player_one) {
this.player_one = player_one;
}
public Player getPlayer_two() {
return player_two;
}
public void setPlayer_two(Player player_two) {
this.player_two = player_two;
}
#Override
public String toString() {
return String.format("Right now are playing %s VS %s",player_one.getName(), player_two.getName());
}
}
public class PlayerTest {
public static void main(String[] args) {
Player peter = new Player("Peter");
Player anna = new Player("Anna");
Match tennisMatch = new Match(peter, anna);
System.out.println(tennisMatch.toString());
}
}
I static field (variable) only exists once for all instances of your class. Therefore what you try does not work by design.
What value would you expect the field to have after you created three different instances of this class using different parameters?
A final variable cannot be changed once it got initialized. For static variables this happens before the first instance of the class is even constructed. At the moment the constructor is executed the field cannot be changed anymore.
To initialize a static final variable you have to assign a value directly at the definition using the = operator or you have to do it in a static initializer which looks like this:
public class FooBar {
public static final String STATIC_VARIABLE;
static {
STATIC_VARIABLE = "Hello World";
}
}
You can make it like this:
private static final NAME;
public Player(String name){
NAME = name;
}
A final varible can be initialized once only if it wasn't initialized yet.
So in this way the constructor is helping you make it.