Alpha
Alpha

Reputation: 14076

How to access variable from another class directly(i.e. without using class name or object)?

Suppose, I've a class TestA which has variable int Age like -

class TestA{
  int Age = 25;
}

and I want to access it from class TestB without using class name(in this case, I'll have to declare Age as static) and without creating object of TestA

How can we achieve this in Java?

Note: TestB is not subclass of TestA

Upvotes: 1

Views: 110

Answers (1)

SMA
SMA

Reputation: 37063

Define that field as static and do something like:

 import static TestA.Age;

 class TestB {
    public void test() {
        System.out.println(Age);
    }
 }

Upvotes: 4

Related Questions