简体   繁体   中英

Can not access public instances from other class

I have two instances: socket and packet as public in main class but I can not access them from other class, and they are in the same package.

I get: cannot find symbol for both of them.

    public class enviar extends TimerTask {

    public void run() {    
           socket.send(packet);
    }

    }
    public class UDP_Client {

    public static DatagramSocket socket;
    static InetAddress address;
    public static DatagramPacket packet;

    public static void main(String args[]){


    final int puerto = 3000;

    try{   

    socket = new DatagramSocket();
    address = InetAddress.getByName("localhost");

    byte[] buf = payload.MSG.getBytes();
    packet = new DatagramPacket(buf, buf.length, address , puerto);

    while(true){
        Timer timer = new Timer();
        timer.schedule(new enviar(), 0, 50);
    }

    }catch(IOException e){
        System.out.println(e);
    }

    }
    }

Thanks mates!!

The issue is that you are not telling Java where to find the socket and packet fields. If you specify the class that contains them, it will resolve your issue. Your code should look something like this:

UDP_Client.socket.send(UDP_Client.packet);

This will work, but you can also statically import the fields, in the enviar file, so that you don't need the class name identifier.

import static package.to.UDP_Client.socket;
import static package.to.UDP_Client.packet;

Then you could just leave your code as-is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM