MrDuk
MrDuk

Reputation: 18262

Why can't I call new from within a static method?

I have some utility functions that I've declared as static, as they are not to be instantiated, only used for utilities. I would like to create a generator method that can generate objects, but in the same static utility context.

public class PeerConnection {

    public class _Heartbeat{
        protected String beat = "HB_000";
        protected String ack  = "HB_001";
        protected String msg  = null;

        protected Date beatTime = null;
        protected Date ackTime  = null;
        protected short missedBeats = 0;
        protected short MAX_MISS = 3;
    }

    public _Heartbeat heartbeat = null;
    //map of heartbeat objects per Peer connection
    public static List<_Heartbeat> Heartbeats = new ArrayList<_Heartbeat>();

    public static void GenerateHeartbeat(){
        Heartbeats.add(new _Heartbeat());
    }

My reasoning, is I want to call this from a SendHeartbeat method:

   private static int SendHeartbeat(PeerConnection peer){
        int acks = 0;
        PeerConnection.GenerateHeartbeat();
        PeerConnection._Heartbeat hb = peer.Heartbeats.get(peer.Heartbeats.size() - 1);
        hb.msg = hb.beat;

        while (acks <= 0 && hb.missedBeats < hb.MAX_MISS){
         [...]
        }
   }

I get the concept of why static works this way, but I'm thinking there has to be a work around for this scenario.

Upvotes: 0

Views: 98

Answers (3)

Tahar Bakir
Tahar Bakir

Reputation: 716

Documentation : nested classes

I think your question is more about nested classes than static stuff. Give back to Caesar what is Caesar's : A realy good answer to your problem here

So in your case you have two option :

 public static class _Heartbeat{ ... }

or

public static void GenerateHeartbeat(PeerConnection p){
    Heartbeats.add(p.new _Heartbeat());
}

private static int SendHeartbeat(PeerConnection peer){
    int acks = 0;
    PeerConnection.GenerateHeartbeat(peer);
    PeerConnection._Heartbeat hb = peer.Heartbeats.get(peer.Heartbeats.size() - 1);
    hb.msg = hb.beat;

    while (acks <= 0 && hb.missedBeats < hb.MAX_MISS){
     [...]
    }
}

Upvotes: 0

Ilja KO
Ilja KO

Reputation: 1616

You need an actual object of your Peer class to instannciate the inner class as this class belongs to an object. Just simply as that...

Upvotes: 0

stripybadger
stripybadger

Reputation: 5009

_Heatbeat is not a static class, so any instance of it is explicitly tied to an instance of the PeerConnection class. I.e. to instantiate _Heartbeat you need an instance of the PeerConnection class.

One option is to make _Heartbeat a static class (i.e. public static class _Heartbeat, which I think is probably what you want.

Another option is to instantiate both together like this new PeerConnection().new _Heartbeat() (I saw this in the java certification exam, but I hate it and never use it so I may not be remembering the syntax correctly).

Upvotes: 2

Related Questions