Java calling object in method outside of main - java

I have a simple problem that I've been stuck on for some time and I can't quite find the answer to. Basically, I'm creating an object and trying to access the variables without using static variables as I was told that is the wrong way to do it. Here is some example code of the problem. I receive an error in the first class that can not be resolved to a variable. What I would like to be able to do is access t.name in other methods outside of the main, but also in other classes as well. To get around this previously I would use Test2.name and make the variable static in the Test2 class, and correct me if I'm wrong but I believe that's the wrong way to do it. Any help would be greatly appreciated =)
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
public class Test2 {
String name;
public Test2 (String nm) {
name = nm;
}
}

I see others have posted code snippets, but they haven't actually posted why any of this works (at the time of this writing.)
The reason you are getting a compilation error, is that in your method
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
Variable t's scope is just that method. You are defining Test2 t to only be in the main(String[] args) method, so you can only use the variable t in that method. However, if you were to make the variable a field, like so, and create a new instance of the Test class,
public class Test {
Test2 t;
public static void main(String[] args) {
Test test = new Test();
test.t = new Test2("Joe");
test.displayName();
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
Then you should no longer be getting any compilation errors, since you are declaring the variable t to be in the class Test scope.

You may give the reference to your test object as an argument to method displayName:
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println("Name2: " + test.name);
}
}
Note: I also made displayName a static method. From within your main method you can only access static methods without reference.

Modify the Test class to this
public class Test {
private static Test2 t;
public static void main(String[] args) {
t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}

Use a getter for your purpose. This is a side solution to your problem, but generally this is how you should retrieve instance variables, using getters.
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println(test.getName());
}
}
public class Test2
{
private String name;
public Test2 (String nm)
{
name = nm;
}
public String getName()
{
return name;
}
}
Always remember, variables in your class should be private. That protects it from access from outside the class. Hence, getters are the only way to access them. And setters or constructors to initialize them.

Fewer statics the better I reckon.
I would Instantiate Test and call displayName on the instance of it, then pass the instance of Test2 to displayName.
But it does depend on what the overall aim is

Related

where to declare classes and functions in java

public class demo
{
public static void main(String[] args)
}
I just started to learn java, I have c++ experience, and the layout confuses me. for example if I declare a function in the demo class would that make it a function or method. also if I want to declare a class can I declare it outside the demo class or it must be inside the demo class.
thank you.
You have already declared it. The thing you are missing is your function body.
public static void main(String[] args)
should be
public static void main(String[] args){
//DO Some Stuff
}
Now here is some additional info:
The main function will be started whenever the application is started and the
String[] args
are the arguments that you are going to pass while starting the application.
You can declare as many functions as you want within your class
public class demo{
public static void main(String[] args){
//Do Some Stuff
}
private void someFunction(){
//Do Some Stuff
}
}
For more you can start learning some basics from the internet. There are tons of tutorials. Hope that helps. :)
you can write code like that
public class Emp{
//Instance variable or class level variable even variable as static
String id;
String name;
//static variable
static int count=0;
{
//non static block
}
static{
// static block
}
public Emp(){
//default constructor
}
//parameterized constructor
public Emp(String id, String name){
this.id=id;
this.name=name;
}
// Non-Static Method
public String getId(){
return id;
}
public String getName(){
return name;
}
//Main method
public static void main(String[] args){
//Instance of class
Emp emp=new Emp("1","Xyz");
System.out.println(emp.getId());
System.out.prinln(emp.getName());
}
}
In Java there are no functions. There are only methods.
You can declare methods inside of class definitions. And methods can be static or not static. Just like in C++.
Also there's no need for header files.
Example:
public class Demo {
// This is a constructor
public Demo() {
}
// This is a non-static method
public void method() {
}
// This is a static method.
// (It's also a special entry point to start the program)
public static void main(String[] args) {
}
}
I think it's safe to say that Java is much simpler than C++.
Ps. I capitalized Demo because according to Java's camel case convention, classes should start with an uppercase letter and methods with lowercase.

Accessing objects of other classes java

I want to access an object i created in a new class but it returns that the object " cannot be resolved".
thanks for anyone who helps:)
here is my code :
public class lion {
int weight;
int height;
String color;
double roardecibles;
public void lioncolor() {
System.out.println(color);
}
}
public class blacklion {
lion blackLion;{
blackLion = new lion();
blackLion.weight =4;
blackLion.height =3;
blackLion.color = "black";
blackLion.roardecibles = 5.5;
}
}
public class zoo {
public static void main(String[] args) {
blackLion.lioncolor(); //here it dosent work//
}
}
There's a difference between an object and a class. Think of a class as a blueprint, that's what you did when you defined it in public class blacklion. But you didn't actually build something with the blueprint. To create an object you have to instantiate it, using the new keyword.
public static void main(String[] args) {
blacklion lion = new blacklion();
lion.lioncolor(); //here it dosent work//
}
Usually, you want to instantiate an Object of your class that you can then access from where u created it. If you want to access methods or variables of a class directly you want to declare those as public and static.
Hey looks like you should check out this resource:
https://docs.oracle.com/javase/tutorial/
Specifically the section of how classes work:
https://docs.oracle.com/javase/tutorial/java/concepts/class.html
this code
public static void main(String[] args)
{
blackLion.lioncolor(); //here it dosent work//
}
needs an instance of the object in order to call the lioncolor() method

Why does inherited public method manipulate the super class's private property instead of the child class?

In the code below, when I run Test2, why does it print null instead lol? It seems that the config method modifies the a property of class Test instead of Test2.
But what's the meaning of inheriting the public methods which manipulate private properties then, why did they design Java like this?
EDIT:
Class Test shall not be modified. What I want to do is to reuse the config method. I define a private property a for Test2, but config just ignores it and uses the one of Test. Shouldn't a method use the property of the class it is in instead of that of the inherited super class?
public class Test {
private String a;
public void config() {
a = "lol"
}
}
public class Test2 extends Test {
private String a;
public void print() {
config();
System.out.println(a);
}
public static void main(String[] args) {
print()
}
}
The purpose is, in short, encapsulation. You don't need to, and can't, access something that is private from outside of the class. The accepted pattern of doing what you want is with getters/setters:
public abstract class Test {
public void config() {
setA("lol");
}
public abstract void setA(String value);
}
public class Test2 extends Test {
private String a;
public void setA(String value) {
a = value;
}
public void print() {
config();
System.out.println(a);
}
public static void main(String[] args) {
new Test2().print();
}
}
It seems that the config method modifies the a property of class Test instead of Test2.
That's right.
why does it print null instead lol?
You have two variables with the same name. One is in the superclass Test, another is in the subclass Test2. Both are named a but they refer to different things.
The method config() in the superclass references the superclass a and the print() method in the subclass references the subclass a. Since the variables are private, neither method can see the variable in the other class.
why did they design Java like this?
This is the nature of private. Nobody else can see it.
It looks to me like you actually desired the behavior of a protected variable:
public class Test {
protected String a;
public void config() {
a = "lol"
}
}
public class Test2 extends Test {
public void print() {
config();
System.out.println(a);
}
public static void main(String[] args) {
new Test2().print();
}
}
This will print lol.

java - can a class type parameter from a static main class be passed to another class

I have 2 classes the static main class and class B. I'm trying to pass main to B, where there is a method that sets fields.
Can this be done?
If so, could you please provide examples?
public static void main(String[] args) {
ArrayList a = new ArrayList()
class b = new class()
b.update(b);
}
class a {
public void update(ArrayList a) {
//updates the encapsulated arrayList field
}
}
The error message keeps on saying that one is static and the other is non-static, but they should be pointing the same object
I'm not entirely sure what you are trying to do, but here is an example that shows that you can pass an instance of the main class into another class:
public class A {
private String str = null;
public static void main(String[] args) {
A a = new A();
B b = new B(a);
System.out.println(a.getStr());
}
public String getStr() {
return this.str;
}
public void setStr(String str) {
this.str = str;
}
}
public class B {
public B(A a) {
a.setA("hello");
}
}
Running this code will print out hello.
main is static and public, so you can call it from any other class as any other public static method: statically.
if you have a class A that contains a
public static void main(String[] args)
method, then class B can call this method like
A.main(s);
where s is String[]
your question is far from clear, so I suggest you to add more code samples to make it clear what you're really trying to do.

public static void main () access non static variable

It is said that non-static variables cannot be used in a static method. But public static void main does. How is that?
No, it doesn't.
public class A {
int a = 2;
public static void main(String[] args) {
System.out.println(a); // won't compile!!
}
}
but
public class A {
static int a = 2;
public static void main(String[] args) {
System.out.println(a); // this works!
}
}
or if you instantiate A
public class A {
int a = 2;
public static void main(String[] args) {
A myA = new A();
System.out.println(myA.a); // this works too!
}
}
Also
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works too!
}
}
will work, since a is a local variable here, and not an instance variable. A method local variable is always reachable during the execution of the method, regardless of if the method is static or not.
Yes, the main method may access non-static variables, but only indirectly through actual instances.
Example:
public class Main {
public static void main(String[] args) {
Example ex = new Example();
ex.variable = 5;
}
}
class Example {
public int variable;
}
What people mean when they say "non-static variables cannot be used in a static method" is that non-static members of the same class can't be directly accessed (as shown in Keppils answer for instance).
Related question:
Accessing non-static members through the main method in Java
Update:
When talking about non-static variables one implicitly means member variables. (Since local variables can't possible have a static modifier anyway.)
In the code
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works!
}
}
you're declaring a local variable (which typically is not referred to as non-static even though it doesn't have a static modifier).
The main method does not have access to non-static members either.
final public class Demo
{
private String instanceVariable;
private static String staticVariable;
public String instanceMethod()
{
return "instance";
}
public static String staticMethod()
{
return "static";
}
public static void main(String[] args)
{
System.out.println(staticVariable); // ok
System.out.println(Demo.staticMethod()); // ok
System.out.println(new Demo().instanceMethod()); // ok
System.out.println(new Demo().instanceVariable); // ok
System.out.println(Demo.instanceMethod()); // wrong
System.out.println(instanceVariable); // wrong
}
}
This is because by default when you call a method or variable it is really accessing the this.method() or this.variable. But in the main() method or any other static method(), no "this" objects has yet been created.
In this sense, the static method is not a part of the object instance of the class that contains it. This is the idea behind utility classes.
To call any non-static method or variable in a static context, you need to first construct the object with a constructor or a factory like your would anywhere outside of the class.
More depth:
Basically it's a flaw in the design of Java IMO which allows static members (methods and fields) to be referenced as if they were instance members. This can be very confusing in code like this:
Thread newThread = new Thread(runnable);
newThread.start();
newThread.sleep(1000);
That looks like it's sending the new thread to sleep, but it actually compiles down into code like this:
Thread newThread = new Thread(runnable);
newThread.start();
Thread.sleep(1000);
because sleep is a static method which only ever makes the current thread sleep.
Indeed, the variable isn't even checked for non-nullity (any more; it used to be, I believe):
Thread t = null;
t.sleep(1000);
Some IDEs can be configured to issue a warning or error for code like this - you shouldn't do it, as it hurts readability. (This is one of the flaws which was corrected by C#...)
**Here you can see table that clear the access of static and non-static data members in static and non-static methods. **
You can create non-static references in static methods like :
static void method() {
A a = new A();
}
Same thing we do in case of public static void main(String[] args) method
public class XYZ
{
int i=0;
public static void increament()
{
i++;
}
}
public class M
{
public static void main(String[] args)
{
XYZ o1=new XYZ();
XYZ o2=new XYZ();
o1.increament();
XYZ.increament(); //system wont be able to know i belongs to which object
//as its increament method(static method)can be called using class name system
//will be confused changes belongs to which object.
}
}

Categories