What is wrong with my code? Compiler says non static variable cannot be referenced from a static context
package nestedclass;
public class Nestedclass {
class Student {
String name;
int age;
long roll;
public Student(String name, int age, long roll) {
this.name = name;
this.age = age;
this.roll = roll;
}
public void show() {
System.out.println("name : "+name+" age : "+age+" roll : "+roll);
}
}
public static void main(String[] args) {
//Nestedclass=new Nestedclass();
Student ob=new Student("ishtiaque",10,107060);
ob.show();
// TODO code application logic here
}
}
The nested Student class isn't static, that's why the compiler complains. There are a couple of ways to get out of this situation: make Student static, or instantiate Nestedclass and provide a nonstatic method in Nestedclass that does the actual work on an instance of Student, and that you call from main:
private void run() {
Student ob = new Student("ishtiaque", 10, 107060);
ob.show();
}
public static void main(String[] args) {
new Nestedclass().run();
}
or, if you like oneliners you could also do
public static void main(String[] args) {
new Nestedclass().new Student("ishtiaque", 10, 107060).show();
}
Personally I prefer the second method (with the helper method) as it's easier to refactor afterwards.
Your inner class is not declared as static; therefore, you cannot access it from the static method main. Change your inner class declaration to static class Student
You need to initiate the static class then Use the new of that class in order to initiate the their inner none classes. Or you can declare your Student inner class as static class.
first solution
Student ob = new Nestedclass().new Student("ishtiaque", 10, 107060);
second solution
static class Strung {...}
Hope that helps.
this will work
public class Student
{
String name;
int age;
long roll;
public Student(String name, int age, long roll) {
this.name = name;
this.age = age;
this.roll = roll;
}
public void show()
{
System.out.println("name : "+name+" age : "+age+" roll : "+roll);
}
public static void main(String[] args) {
Student ob=new Student("ishtiaque",10,107060);
ob.show();
}
}
Related
This question already has answers here:
Modifier static is only allowed in constant variable declarations
(2 answers)
Closed 2 years ago.
My task is : Call the ‘setGrade’method to assign to the grade variable of S1 the value of 11
the code is:
public class student {
private String name;
private int age;
private int grade;
private double average;
private boolean disability;
private void printStudentInfo(){
//Data Encapsulation is methods of the public interface provide access to private data, while hiding implementation.
System.out.println("Name: "+name+",Age: "+age+",Grade: "+grade+",Average: "+average +" Disability: "+disability);
}
public void setGrade(int newGrade){
grade=newGrade;
}
public int getGrade(){
return grade;
}
//this part was given from the question
//from here
public class StudentTester{
public static void main(String[] args){
student S1 = new student();
student S2 = new student();
//to here
S1.setGrade(12);
}
}
}
Every time I run my program it gives me an error
modifier 'static' is only allowed in constant variable declarations
The tester class should contain the main method along with other static classes and methods.
public class StudentTester{
public static void main(String[] args){
student S1 = new student();
student S2 = new student();
S1.setGrade(12);
}
public static class student {
private String name;
private int age;
private int grade;
private double average;
private boolean disability;
private void printStudentInfo(){
//Data Encapsulation is methods of the public interface provide access to private data, while hiding implementation.
System.out.println("Name: "+name+",Age: "+age+",Grade: "+grade+",Average: "+average +" Disability: "+disability);
}
public void setGrade(int newGrade){
grade=newGrade;
}
public int getGrade(){
return grade;
}
}
}
Also check, Static Classes In Java
public class Sample1 {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
Sample1 s1= new Sample1();
s1.setName("Abc");
}
}
public class Sample2 {
public static void main(String[] args) {
Sample1 n2= new Sample1();
System.out.println(n2.getName());
}
}
I have two classes Sample1 and Sample2 two. I am allocating string value using setter method and returning in another class by using getter method, but an output is null. Why null is an output and how to get string value from one call to another class?
I think you misunderstood the main method, maybe I am wrong, however only one main method is executed.
If you run Sample2.main - on Sample1 you are not setting a name so it is null (Sample1.main is never executed).
If you run Sample1.main - Sample1 is created and assigned a name.
So either assign the name in the Sample2.main:
public static void main(String[] args) {
Sample1 n2= new Sample1();
n2.setName("xxx");
System.out.println(n2.getName());
}
or do it via constuctor.
public class Sample1 {
private final String name;
public String getName() {
return name;
}
public Sample1(String name) {
this.name = name;
}
}
Consider the code :
Sample1 n2= new Sample1();
System.out.println(n2.getName());
Here the Name is not set , So you need to set the name before getting the name.
Sample1 n2= new Sample1();
n2.setName("name goes here");
System.out.println(n2.getName());
Also, you can try parameterized constructor in the Sample1 class and access like in sample2 class:
Sample1 n2= new Sample1("your name goes here");
System.out.println(n2.getName());
The constructor will be :
public Sample2(String name){
this.name = n;
}
3 thing you can add method in Sample1 class and access it in Sample2 class.
I don't want to set String value in Sample2 class, need to assign string value in Sample1 only, after that i need that string value in Sample2 class
public class Sample1 {
private String _name;
public String getName() {
return _name;
}
private setName(String name) {
_name = name;
}
public SetNameHelper(){
setName("somestring");//You will be setting the name in Sample 1
}
}
public class Sample2 {
public static void main(String[] args) {
Sample1 n2= new Sample1();
n2.SetNameHelper();
System.out.println(n2.getName());//You will be getting Name in Sample 2 class
}
}
class Sample2 {
Sample1 sample1;
Sample2(Sample1 sample){
this.sample1 = sample;
}
private String getSample1Name() {
return this.sample1.getName();
}
public static void main(String[] args) {
Sample1 sample1 = new Sample1();
sample1.setName("Abc");
Sample2 n2= new Sample2(sample1);
System.out.println(n2.getSample1Name());
}
}
I think I understand you confusion: you mistake a main function for a constructor!
I noticed that you created a main function in each class, whose only role is to create an instance and set the internal fields of the class. It's probably a Constructor you were looking for.
Here's the deal:
A main method is the entry point of a program. It just stays, to run me: begin executing this code. You probably (99.9% of the case) need only one main method per project.
A Constructor is a method which creates an instance of, each class, i.e. an object you can manipulate elsewhere in your code. Read up on Object-Oriented Programming
So here is your example, fixed (I believe), in a way that can bring sample1 value into an sample2, as you say:
public class Sample1 {
public String name;
public String Sample1(String initialName){
this.name = initialName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Sample2{
public String name;
public String Sample2(String initialName){
this.name = initialName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ProgramEntryPoint{
public static void main(String[] args) {
Sample1 s1 = new Sample1("a name");
System.out.println("Initial sample1 name: " + s1.getName());
s1.setName("a New Name!");
System.out.println("New sample1 name: " + s1.getName());
Sample2 s2 = new Sample2(s1.getName());
System.out.println("Initial sample2 name: " + s2.getName());
}
}
Which, once you run ProgramEntryPoint.main, will print:
Initial sample1 name: a name
New sample1 name: a New Name!
Initial sample2 name: a New Name!
This is all simple Java stuff, you should read up a few basic tutorials (the ones on oracle website are a good start)
I am a complete beginner in java, so please forgive me if this question is not up to the standard of this website:
class person{
String name;
int age;
}
class teacher extends person{
person s1=new person();
teacher t1=new teacher();
t1.age=56;
}
Here I am trying to access the variable age and name of class to assign them values person, which happens to be the super class of person. But the compiler is giving error. I even tried to make the name variable and age variable as public. But the compiler is still reporting an error. I want to know the reason why I can't access superclass variable in subclass directly and assign values to them.
You are not allowed to write arbitrary code directly within a class body. The closest thing to what you have written is
class teacher extends person{
person s1=new person();
teacher t1=new teacher();
{
t1.age=56;
}
}
This is called the instance initializer block.
In general, it is not a good idea to access variables directly. Consider using something like the code below.
Test driver
package com.example.input;
public class TestPeople {
public static void main(String[] args) {
Person s1 = new Person();
s1.setName("student 1").setAge(19);
Teacher t1 = new Teacher("Dr. Fun",0);
t1.setAge(56);
System.out.println("Student " + s1.getName() + ", " + s1.getAge());
System.out.println("Teacher " + t1.getName() + ", " + t1.getAge());
}
}
Class Person
package com.example.input;
public class Person {
private String name;
private int age;
public Person() {};
public Person(String aName, int anAge) {
setName(aName).setAge(anAge);
}
public String getName() {return name;}
public int getAge() {return age;}
public Person setName(String aName) { name = aName; return this;}
public Person setAge(int anAge) { age = anAge; return this;}
}
Class Teacher
package com.example.input;
public class Teacher extends Person {
public Teacher() {
super();
}
public Teacher(String aName, int anAge) {
super(aName, anAge);
}
}
Actually you are making an assignment of variable of external class in existing class body which is not legal.Make the assignment in a method or constructor or in a anonymous block.
class person{
String name;
int age;
}
class teacher extends person{
person s1=new person();
teacher t1=new teacher();
// t1.age=56; Error here
public teacher()
{
t1.age=56;
}
//or method
public void setAge()
{
t1.age=56;
}
}
do whatever suits your program and you.
I would like to call the Salarycal() method from Employee inner class employeeInfo to class Exc
public class Employee {
public class employeeInfo{
int id;
String name;
int Salary;
public employeeInfo(int id,String name,int Salary){
this.id=id;
this.name=name;
this.Salary=Salary;
System.out.println(id+name+Salary);
}
public int Salarycal(){
int totalSalary =0;
int b=getId();
........
}
}
import Employer.Employee.employeeInfo;
public class Exc {
public static void main(String[] args) {
//want to access the salarycal() method in this class
}
}
this is how I would usually invoke a method of inner class
Inner inner = new Outer().new Inner();
inner.methodToInvoke();
Like #Ashish said:
public static void main(String[] args) {
new Employee().new employeeInfo().Salarycal();
}
PS. Read about Code Conventions for the Java TM Programming Language
In my main class, I have a static method which I pass the array into. It is a static method because if I want to pass something from the main class body to this method, it must be static. In a separate class I have a series of getters and setters (which must be non static ).
How can I pass my static array in and use the non-static getters and setters?
EDIT- In the arraySearch method...I cannot pass in the Person Array and access the getters in the Person Class
public class Main {
public static void main(String[] args) {
Person One = new Person("Alice","Foo", 22, false);
Person Two = new Person("Alice", "Foo",22, false);
Person Three = new Person("Bob","Bar",99, false);
Person Four = new Person("Joe","Blogs",64, false);
Person Five = new Person("Jane", "Joe",42, false);
Person [] People = {One,Two,Three,Four,Five};
printArray(People);
}
public static void printArray(Person [] People)
{
for(int i=0;i<People.length;i++)
{
System.out.println(People[i]);
}
}
public void arraySearch(Person [] People)
{
for(int i=0;i<People.length;i++) //Searches the Array of Objects
{
String firstName = Person.getFirstName();
String secondName=Person.getSecondName();
if((firstName.equals("Joe")&&secondName.equals("B" + //Searches for Joe Blogs and Jane Joe
"logs"))|| ((firstName.equals("Ja" +
"ne")&&secondName.equals("Joe"))))
{
int age=Person.getAge();
Person.setAge(age+1); //Increments Age by 1
}
}
}
}
public class Person {
private String mfirstName;
private String msecondName;
private int mage;
private boolean misRetired;
public Person(String firstName,String secondName,int age, boolean isRetired)
{
mfirstName=firstName;
msecondName=secondName;
mage=age;
misRetired=isRetired;
}
//GETTERS
public String getFirstName()
{
return mfirstName;
}
public String getSecondName()
{
return msecondName;
}
public int getAge()
{
return mage;
}
public boolean getRetired()
{
return misRetired;
}
//SETTERS
public void setFirstName(String firstName)
{
mfirstName=firstName;
}
public void setSecondName(String secondName)
{
msecondName=secondName;
}
public void setAge(int age)
{
mage=age;
}
public void setRetired(boolean isRetired)
{
misRetired=isRetired;
}
//STRING
public String toString()
{
return (mfirstName+"-"+msecondName+"-"+mage+"-"+misRetired);
}
}
This is very basic Java question. You need to create instance of object containing setter/getters from your static method. You can also pass static array in setter of this object. Then you should be able to call those getter/setter methods.
public class Main
{
public static void main(String[] args)
{
MyClass myclass = new MyClass();
myclass.setArgs(args);
System.out.println(myclass.getArgs());
}
}
public class MyClass
{
private String[] args;
public String[] getArgs()
{
return args;
}
public void setArgs(String[] args)
{
this.args= args;
}
}
You have to create an object instance from the class with the getters.
The Amit answer is correct; this just has some more info and more closely matches the situation you describe in your question.
Your basic premise "It is a static method because if I want to pass something from the main class body to this method, it must be static." is wrong. The method to which you pass the array does not need to be static. Here is some code:
public final class Main
{
private static final String[] staticOTron =
{
"one",
"two",
"three"
};
public static void main(final String[] args)
{
String[] hootBerrySause;
Tool tool = new Tool();
tool.setStaticOTron(staticOTron);
hootBerrySause = tool.getStaticOTron();
for (String value : hootBerrySause)
{
System.out.println("Value: " + value);
}
}
}
// this can be in a different file.
public final class Tool
{
private static String[] staticOTron;
public void setStaticOTron(final String[] newValue)
{
staticOTron = newValue;
}
public String[] getStaticOTron()
{
return staticOTron;
}
}
Sunil kumar from vmoksha
Your asking deeper navigation
Just create the instance of particular or create the getter &and setter in the main
class