Как использовать переменную одного класса в другой класс, используя Java? - PullRequest
0 голосов
/ 16 июля 2010

У меня есть два файла классов.В этом первом файле я сохранил класс aaa firl, а в следующем текстовом файле я сохранил файл класса bbb. Я хочу использовать переменную класса aaa в классе bbb.Как его использовать.

Примечание. Если я помещу строковую переменную в качестве общедоступной, то отобразится ошибка.

class aaa{
    public void method{
        String value="as some output";
        string other="it has some output";
    }
}
public static void main(String args[]){
    aaa obj=new first();
    bbb object=new second();
}

class bbb{
    aaa obj2=new aaa();
    System.out.println(obj2.value); //It gives error here also
}

Пожалуйста, предложите идеи.Заранее спасибо.

Ответы [ 4 ]

2 голосов
/ 16 июля 2010

Вам не хватает базовых знаний о Java, возможно, прочитайте несколько учебников в Интернете.

// use capitals for the first letter, conventions are good ;)
public class Aaa{
    // I think this is what you meant, you want member variables, add public if you
    // want them to be accessible anywhere
    public String value="as some output";
    public String other="it has some output";

    // missing brackets
    public void method() {
        // do something/anything
    }
}

public class Bbb{
    // you need to put this in a main... without getting exceptions
    public static void main(String args[]){
        Aaa obj2=new Aaa();
        // now you can access the field value, since it's public
        System.out.println(obj2.value); //error should be gone now
    }
}

public class TestMain{
    public static void main(String args[]){
        // first and second aren't classes, you meant Aaa and Bbb?
        Aaa objA=new Aaa();
        Bbb objB=new Bbb();
    }
}
1 голос
/ 16 июля 2010

Чтобы ответить на ваш вопрос, значение является локальной переменной в методе Bbb.method.Чтобы получить к нему доступ из другого класса, это должна быть переменная instance класса (объявленная в классе, но вне какого-либо метода) и доступная (общедоступная или пакетная (по умолчанию)), либо приватная с помощью getter / setterметоды)

// note that I've renamed classes to follow the convention of uppercasing class names.
// this makes the code much easier to read.
class Aaa {
    public String value = "instance value initialized when the class loads (first use)";
    public String other = null;

    // a method declaration must have parentheses, even if it takes no parameters
    public void method() {
        other = "instance value, initially null, set by calling method";
    }
}

class Bbb {
    Aaa aaaInBbb = new Aaa();

    public void method(){
        // every statement (except variable declarations) must be in a method
        System.out.println(aaaInBbb.value); // access the public value in aaaInBbb
    }
}

class C {
    // note that main(...) must be in a class as well - as all methods in Java must
    public static void main(String[] args) { // convention also puts [] next to the type
        Aaa aaa = new Aaa(); // this variable is never used.
        Bbb bbb = new Bbb();

        bbb.method();  // causes instance of Bbb to print out aaaInBbb.value
    }
}

Я добавил несколько дополнительных комментариев к синтаксису и стандартным соглашениям о коде, которые помогут вам при изучении Java.

1 голос
/ 16 июля 2010

Ваш класс aaa не имеет открытой переменной-члена, которая называется value. В вашем методе есть значение локальной переменной, которое вы не сможете использовать.

В основном есть два варианта:

а) Использовать метод получения.

class Aaa
{
    //...
    public String getValue()
    {
        return this value;
    }
}

//...
Aaa a = new Aaa();
String test = a.getValue();
//...

b) Использовать открытую переменную-член.

class Foo
{
   // ...
   public String value = "bar"; 
   //...
}

//...
Aaa a = new Aaa();
String test = a.value;
//...

Я рекомендую вам использовать первый.

0 голосов
/ 24 января 2017

Вы можете просто объявить переменную и инициализировать значение переменной в method1 и, наконец, расширить этот класс.

class aaa{
String value;
    public void method(){
         value="as some output";       
    }
}

class bbb extends aaa{  
     public void method2(){
         System.out.println(value); //Output is "as some output";      
    }      

    public static void main(String as[]){
     bbb obj2=new bbb();
     obj2.method();   //getting the value of string value
     obj2.method2(); //print the value in method2
     }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...