Accessing objects of other classes java - 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

Related

Access class variable using Interface type

I've following class
class MyClass implements Intrfc {
String pickmeUp = "Its Me";
public static void main(String[] args){
Intrfc ob = new MyClass();
ob.pickmeUp; ---> How can I access this way ?
}
}
Is there any way to access class variable using Interface type ?
Is there any way to access class variable using Interface type ?
No. That is the whole point of an interface.
And yes, interfaces only give you behavior (methods), not "state" (variables/fields). That is how things are in Java.
Of course, you can always use instanceof to check if the actual object is of some more specific type, to then cast to that type. But as said, that defeats the purpose of using interfaces!
No, you can't access the class variable using interface type, but the interface can define method that can access to the variable.
interface Intrfc {
public String getPickmeUp();
}
class MyClass implements Intrfc {
String pickmeUp = "Its Me";
public String getPickmeUp(){
return pickmeUp;
}
public static void main(String[] args){
Intrfc ob = new MyClass();
ob.getPickmeUp();
}
}
In this definition:
class MyClass implements Intrfc {
String pickmeUp = "Its Me";
}
the field pickmeUp is not even a member of Intrfc interface, so there is no possibility to reach for it using just the interface. pickmeUp is a member of a concrete class - MyClass.
If you want to use the method of a class using the object of an interface you can do it as follows:
//Interface:
public interface TestOne {
int a = 5;
void test();
static void testOne(){
System.out.println("Great!!!");
}
default void testTwo(){
System.out.println("Wow!!!");
}
}
//-------------------
//Class implementing it:
package SP;
public class TestInterfacesImp implements Test1, TestOne{
#Override
public void test() {
System.out.println("I Love java");
}
public void testM() {
System.out.println("I Love java too");
}
public static void main(String[] args) {
TestOne.testOne();
TestOne obj = new TestInterfacesImp();
obj.testTwo();
TestInterfacesImp objImp = new TestInterfacesImp();
objImp.test();
((TestInterfacesImp) obj).testM(); //Here casting is done we have casted to class type
}
}
Hope this helps...

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.

Access public static class' state from a separate class file

I have a public static class within another public class as follows:
public class Foo<A> {
public static class Bar<A>{
A firstBar;
Bar(A setBar){
this.firstBar=setBar;
}
}
public final Bar<A> instanceBar;
public Foo(A actualValue) {
instanceBar = new Bar<A>(actualValue);
}
public Bar<A> getBar() {
return instanceBar;
}
My objective is to access instanceBar's state from a separate class file without a get method and without changing the visibility of firstBar. How do I accomplish this?
For example, the following says not visible.
public class RetrieveFirstBar {
public static void main(String[] args) {
Foo z = new Foo(5l);
Foo.Bar<Long> z2 = z.getBar();
long k = z2.firstBar; //not visible!
}
}
I guess you mean
class Foo<A>
Since you write "A firstBar;" you give package access to the variable:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If you have the RetrieveFirstBar in the same package you will not have visibility problems. But, if you want to access it from everywhere you should write
public A firstBar;

How can I access a method of an "unnamed" class?

public class Test {
public static void main(String[] args) {
DemoAbstractClass abstractClass = new DemoAbstractClass() {
private String val;
#Override
public void runner() {
val = "test";
System.out.println(val);
this.run();
}
public String getVal() {
return val;
}
};
abstractClass.runner();
/**
* I want to access getVal method here
*/
}
}
abstract class DemoAbstractClass {
public void run() {
System.out.println("running");
}
public abstract void runner();
}
Here, I'm declaring an abstract class DemoAbstractClass. I can obviously create a new class that extends this class and add this method to it. But, I would prefer not doing that in my scenario.
Is there any other way to access getVal method in above code??
You can't. You need to make a proper (non-anomous) class out of it. Make it an inner private class if you want to limit its scope.
Alternatively, you could use a StringBuffer and share a referense to it between the methods. Not extremely clean however.
Related question:
Accessing inner anonymous class members
Short of using reflection, you cannot as you have no access to the concrete type of the object to be able to bind the methodcall to
If you don want to do something like this in a sane manner, declare a named class and use that as the type of abstractClass
Unfortunately, if you cannot name the type, you cannot access the methods at the language level.
What you can do, though, is use the reflection API to get a Method object and invoke it on this object.
This, however, is pretty slow. A private class or private interface would be much faster.
I can obviously create a new class that extends this class and add this method to it.
You've already done this; the end result was an anonymous inner class: new DemoAbstractClass() { ... }; If you just moved that declaration into its own class -- you can even make it a private class -- you can access getVal.
Per your example above:
public class Test {
public static void main(String[] args) {
DemoClass abstractClass = new DemoClass();
abstractClass.runner();
/**
* I want to access getVal method here
*/
abstractClass.getVal(); // can do this here now
}
private class DemoClass extends DemoAbstractClass {
private String val;
#Override
public void runner() {
val = "test";
System.out.println(val);
this.run();
}
public String getVal() {
return val;
}
}
}
}
Another option is to make a StringBuilder a member of the main method and use the closure nature of anonymous inner methods:
public static void main(String[] args) {
final StringBuilder value = new StringBuilder();
DemoAbstractClass abstractClass = new DemoAbstractClass() {
#Override
public void runner() {
value.append( "test" );
System.out.println(val);
this.run();
}
};
abstractClass.runner();
// use val here...
String val = value.toString();
}

Java calling object in method outside of main

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

Categories