java - Object cannot be resolved to variable - java

I'm trying to write a very simple, little java program but I'm already stuck at setting the object name.
I have 2 classes, first is Starter:
public class Starter {
public static void main(String args[]) {
Family tester = new Family();
tester.setName(testers);
}
}
If i'm right I create a Family object called tester, then I use the setName method for giving the family a name.
The Family class lookes like this:
public class Family{
String Name;
public void setName(String name){
Name = name;
}
}
But in the starter class at the tester.setName I get this error: tester cannot be resolved to a variable.
Thanks in advance for the answers!

Replace
tester.setName(testers);
with
tester.setName("testers");
As your Family class's setName() method takes a String object and String needs to be created either as above example or as below example:
String testers = new String("testers");
//and then you can use above String object as in your code snippet (as follows)
tester.setName(testers);

Unlike some other programming languages, in Java Strings must be enclosed in double quotes.
Single quotes are used for chars, a primitive data type.
You can change your code within;
tester.setName("testers");

You have some mistake in the setName():
public class Starter {
public static void main(String args[]) {
Family tester = new Family();
// tester.setName(testers);
// variable testers is not defined, you means set the name to "testers"? Try this:
tester.setName("testers");
}
}

Related

How can I use non static variable(object ref) in static method without creating object inside that static method in java?is there any way to do it?

I'm new to Java. I get this error when running the code below
Cannot make a static reference to the non-static field universityObj
But not getting error while using
University universityObj = new University();
The code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
University universityObj;
public static void main(String[] args)
{
University universityObj = new University();
universityObj.name="Robert";
universityObj.stuno=12;
System.out.println(universityObj.name);
System.out.println(University.university_name);
display();
}
public void nonStaticDisplay()
{
System.out.println(name);
System.out.println(stuno);
}
public static void display()
{
universityObj = new University();
System.out.println(universityObj.name);
}
}
Let's go step by step.
The display() method should be non-static because it belongs to and should be used on the specific instance of the University class. Static methods can be used without creating an instance of some class. But in the case of the display() method, it wouldn't makes sense to do that because you need to display the university name, which firstly should be created and assigned.
It's not a good idea to create the object instance University universityObj inside the class in your case. Better to leave it only in the main method.
The university_name name is not static, so you can't access it without the class instance (object) like you're doing right now. University.university_name should be changed to universityObj.university_name.
These steps will bring us to a such piece of code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
public static void main(String[] args) {
University universityObj = new University();
universityObj.name = "Robert";
universityObj.stuno = 12;
System.out.println(universityObj.name);
System.out.println(universityObj.university_name);
universityObj.display();
}
public void display() {
System.out.println(name);
System.out.println(stuno);
}
}
Other things, which you should consider:
Read about encapsulation.
Use code formatting in your IDE. Example for IntelliJ IDEA.
Check the toString() method from the Object class. It's intended exactly for what you're trying to achieve with your display() method.
You might simply pass a reference to the instance you want to be displayed. Like,
public static void display(University universityObj)
{
System.out.println(universityObj.name);
}

Why does my ArrayList only print out the last subclass that was called? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 3 years ago.
I'm currently learning polymorphism in Java, and part of the assignment was to create a program that will print out various subclasses using inheritance and polymorphism. I have tried looking for solutions but I couldn't seem to find anyone else experiencing this issue.
Below is a piece of code that is supposed to print Alex and Alexa respectively. However, the output is, instead, Alexa Alexa.
I have tried debugging by stepping through using Eclipse, but I can't pinpoint what is the mistake. I am truly stumped at this point, I've been trying this question for the past week but to no avail. Please forgive me if this is a simple question but I can't figure out what went wrong. I would truly appreciate any assistance!
import java.util.ArrayList;
public class Human {
protected static String name;
public Human(String name) {
System.out.println("In human constructor");
this.name = name;
}
void greetings() {}
static void print(Human human) {
System.out.println(name);
}
public static void main(String[] args) {
ArrayList<Human> human = new ArrayList<Human>();
human.add(new Man("Alex"));
human.add(new Woman("Alexa"));
for (int i = 0; i < human.size(); i++) {
print(human.get(i));
}
}
}
class Man extends Human {
public Man(String name) {
super(name);
// TODO Auto-generated constructor stub
}
}
class Woman extends Human {
public Woman(String name) {
super(name);
// TODO Auto-generated constructor stub
}
}
There are a couple things wrong here:
name should not be static. You want an instance of name for each instance (object) created.
You are printing the wrong name. You want to print the name of the instance passed into print(). So you would want something like this (you would create a getter method for name):
static void print(Human human) {
System.out.println(human.getName());
}
every Human has his own name, no matter if Man or Woman.
so remove the static keyword from
protected static String name;
This is because you've defined name as a static field. so in every object it will have the same value. just remove the static from name.
protected String name;
when a variable, method, ... is defined static, you can have access to it without creating objects. meanwhile it will have the same value in each object. so if you are modifying a static variable, it will keep the last modification.
take a look at this link for more information.
Do some research on the static context. Here is part of your problem:
protected static String name;
Making name static means that it belongs to the Human class. That means every object of class Human will have the same name.
If you want Human objects to have different names, remove that static modifier.
Next, Human should probably be a POJO, instead of your main class. Something like this:
public class Test {
public static void main(String[] args) {
Human human = new Human("Steve");
System.out.println(human.getName());
}
}
class Human {
private String name;
Human(String s) {
this.name = s;
}
public String getName() {
return this.name;
}
}

Can `greetSomeone("world")` be replaced by `greetSomeone(name)`? Is there any side effect to this change?

I'm new to Java and is trying to learn the concept of inner class. I saw the code below from Java tutorial Oracle. My question is, for
String name = "world";
#Override
public void greet() {
greetSomeone("world");
}
Can greetSomeone("world") be replaced by greetSomeone(name). The reason why I'm asking this question is because I have noticed if greetSomeone("world") is indeed replaced by greetSomeone(name), inside the public void greetSomeone() method, the passed "name" argument will be set to itself. I was just wondering if there are side effect to code like this?
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public void sayHello() {
class EnglishGreeting implements HelloWorld {
String name = "world";
#Override
public void greet() {
greetSomeone("world");
}
#Override
public void greetSomeone(String someone) {
name = someone;
System.out.println("hello " + name);
}
}
HelloWorld eg1 = new EnglishGreeting();
eg1.greet();
}
public static void main(String[] args) {
HelloWorldAnonymousClasses myApp = new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
First of all why is that #Override annotation there?
You will use Override when you want to change the behaviour of the parent's methods. Your parent's methods have no behaviour as it is an interface. As a further note I guess that it will teach you that the signature of an overriden method must always match the one from the parent.
Secondly the design is kind of dodgy. It can be simplified.
Thirdly yes you can refer to the String object name as it is defined in that class and you can access the object's primitive just by calling 'name'. Why will you not get the reference printed when System.out? Because the String object handles that for you ensuring the toString will show you the primitive. When you do System.out.print(myObject); The console will show you the Object default or the overriden toString method.
So if you create an object and you do System.out.print(myObject) you will see the reference. If you override toString returning "test" you will see test.
Technically, name can be passed and name = name; is valid Java.
However, this is a horrible design and was probably used for demonstrative purposes only. Don't do this.

getting the current class object

I have three classes.. A,B,C.
In both classes B and C i have a static string variable "name" which contains the name of B and C, as-
class B
{
static name;
public static void main(String args[])
{
name="Class B";
A.getName();
}
I am calling class A's getName method from class B and C.. Class A is as follows:
class A
{
getName()
{
System.out.println(this class called me);
}
}
class C is:
class C
{
static name;
public static void main(String args[])
{
name="Class C";
A.getName();
}
Now my question is, what code should i use in place of "this class called me" in class A so that i get the name of whichever class calls A! I hope i am clear!!
Your A.getName method cannot know what class's code called it. You have to pass that information into it.
Okay, so that's not strictly true, you could figure it out by generating a stack trace and inspecting that. But it would be a very bad idea. In general, if a method needs to know something, you either A) Make it part of an instance that has that information as instance data, or B) Pass the information into it as an argument.
class A {
getName()
{
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
int lastStackElement = stackTraceElements.length-1;
String callingObjectsName = stackTraceElements[lastStackElement].getClassName();
System.out.println(callingObjectsName + " called me.");
}
}
Modify your code to something like this:
class A
{
getName(String className)
{
System.out.println(className);
}
}
and use it like :
class B
{
static name;
public static void main(String args[])
{
name="Class B";
A.getName(name);
}
}
It sounds like what you're really trying to do is to pass information from one stack frame to another one -- and specifically, from a frame A to a frame B, where A invoked B. This is an easy thing to do, and I think you're over-engineering it.
public class B {
static String name = ...
public static void main(String[] args) {
A.getName(name);
}
}
public class C {
static String name = ...
public static void main(String[] args) {
A.getName(name);
}
}
public class A {
public static void getName(String name) {
System.out.println(name);
}
}
Your approach would require:
Getting the stack trace
Using that to get the calling stack frame, which is element 1 in the stack trace array
Using that to get the class name for the calling method
Using Class.forName to get the Class<?> object
Calling getField("name") on that Class<?> object to get a Field object
(optional but recommended) Confirming that the Field represents static field of type String
calling get(null) on the Field to get its value (the null represents the object for which you want the field -- since the field is static and thus not tied to any object, this argument is ignored), and casting this value down to String
Or, instead you could:
Just pass the name to the function that needs it.
Your approach also requires that the name field be static, since there's no way to get the calling instance (even though you can get the calling instance's class). The simpler approach works even if name is an instance field.

Writing a Java class with instance parameters, retrieve parameters and print results

Basically, I need to create a new simple Java class which retrieves values from my forms (that I have designed as my process and is deployed as a web application), once the method in the Java class is invoked then the Java class should just simply print out the values (e.g. system.println.out...) it got from the form in a console or text file.
Create a class with some instance parameters. Print a line stating the initial values of these parameter(s).
I am new to Java and have just started few days ago but have this requirement as part of a project.
Please someone help to write this Java class.
I recommend you to read some java beginners books (or the javadoc) in order to understand the Class constructor concept in java before trying to do write something wrong.
A rough class may be like this :
public class myClass{
int param1;
int param2;
public myClass(int firstparam, int secondparam){
this.param1 = firstparam;
this.param2 = secondparam;
}
}
public static void main(){
myClass c = new myClass(1,2);
System.out.println(c.param1 + c.param2);
}
If you don't understand this, please learn the java basis..
You can simply create a class and its constructer like:
public class Test {
//a string representation that we will initialize soon
private String text;
//Firstly you have to instantiate your Test object and initialize your "text"
public Test(String text) {
this.text = text;
//System.out.println(text);
//You can print out this text directly using this constructor which also
//has System.out.println()
}
//You can just use this simple method to print out your text instead of using the
//constructor with "System.out.println"
public void printText() {
System.out.println(this.text);//"this" points what our Test class has
}
}
While using this class is like:
public class TestApp {
public static void main(String[] args) {
Test testObject = new Test("My Text");
/*if you used the constructor with System.out.println, it directly prints out
"My Text"*/
/*if your constructor doesn't have System.out.println, you can use our
printText() method //like:*/
testObject.printText();
}
}

Categories

Resources