I am coming from JavaScript, in which callbacks are pretty easy. I am trying to implement them into JAVA, without success.  I have a Parent class:  import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;  public class Server {     ExecutorService workers = Executors.newFixedThreadPool(10);     private ServerConnections serverConnectionHandler;      public Server(int _address) {         System.out.println("Starting Server...");         serverConnectionHandler = new ServerConnections(_address);          serverConnectionHandler.newConnection = function(Socket _socket) {             System.out.println("A function of my child class was called.");         };          workers.execute(serverConnectionHandler);          System.out.println("Do something else...");     } }   Then I have a child class, that is called from the parent:  import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger;  public class ServerConnections implements Runnable {     private int serverPort;     private ServerSocket mainSocket;      public ServerConnections(int _serverPort) {         serverPort = _serverPort;     }      @Override     public void run() {         System.out.println("Starting Server Thread...");          try {             mainSocket = new ServerSocket(serverPort);              while (true) {                 newConnection(mainSocket.accept());             }         } catch (IOException ex) {             Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);         }     }      public void newConnection(Socket _socket) {      } }   What is the right way of implementing the  serverConnectionHandler.newConnection = function(Socket _socket) {     System.out.println("A function of my child class was called."); };   part, in the Parent class, which is clearly not correct?
104469
Is there a way to pass a call back function in a Java method?  The behavior I'm trying to mimic is a .Net Delegate being passed to a function.  I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
105089
I have an abstract Class Monitor.java which is subclassed by a Class EmailMonitor.java.   The method:  public abstract List&lt;? extends MonitorAccount&gt; performMonitor(List&lt;? extends MonitorAccount&gt; accounts)   is defined in Monitor.java and must be overridden in EmailMonitor.java.  I currently have the method overridden in EmailMonitor.java as follows:  @Override public List&lt;EmailAccount&gt; performMonitor(List&lt;EmailAccount&gt; emailAccounts) {     //...unrelated logic     return emailAccounts; }   However, this produces the compile time error:   Name clash: The method performMonitor(List&lt;EmailAccount&gt;) of type EmailMonitor has the same erasure as performMonitor(Lis&lt;? extends MonitorAccount&gt; emailAccounts) of type Monitor but does not override it  EmailAccount is a subclass of MonitorAccount, so (in my mind at least) overriding it in this way makes perfect sense. Seeing as the compiler is not happy with my logic though, How should I go about this correctly while still keeping my compile time checks to make sure that all calls to EmailMonitor.performMonitor() receive Lists of EmailAccount rather than some other type of MonitorAccount?
3278
So, I understand that the following doesn't work, but why doesn't it work?  interface Adapter&lt;E&gt; {}  class Adaptulator&lt;I&gt; {     &lt;E, A extends I &amp; Adapter&lt;E&gt;&gt; void add(Class&lt;E&gt; extl, Class&lt;A&gt; intl) {         addAdapterFactory(new AdapterFactory&lt;E, A&gt;(extl, intl));     } }   The add() method gives me a compile error, "Cannot specify any additional bound Adapter&lt;E&gt; when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick.  Clearly you're just Not Allowed to use the type parameter I there, before the &amp;, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that I isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer.  Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one add() method, so it's not like there's any ambiguity...  Can someone demonstrate the problem for me?
29041
I'm looking for a way to have two separate objects be connected, so that when I move the first object the second one will move also. The term parent is used, but how do I parent a object?
29293
Say I have classes Foo and Bar set up like this:  class Foo { public:     int x;      virtual void printStuff()     {         std::cout &lt;&lt; x &lt;&lt; std::endl;     } };  class Bar : public Foo { public:     int y;      void printStuff()     {         // I would like to call Foo.printStuff() here...         std::cout &lt;&lt; y &lt;&lt; std::endl;     } };   As annotated in the code, I'd like to be able to call the base class's function that I'm overriding. In Java there's the super.funcname() syntax. Is this possible in C++?
51297
I moved a method that sets addError() from a trigger into a Helper class. As I started writing test code for it it seems like the addError() is not actually preventing DML operations for the records that get modified in the helper class.  The information from the SF  states: Marks a trigger record with a custom error message and prevents any DML operation from occurring.  Does this mean that addError() will not work outside of a trigger class?  EDIT  Adding some sample code.  public class MyHelperClass() {     public static void someMethod(Opportunity opp) {         opp.My_Field__c.addError('Some error');         insert opp;     } }   And sample test for it without any asserts:  @IsTest private class MyHelperClass_Test() {     @IsTest     static void someTest() {         Opportunity opp = new Opportunity();         opp.Name = 'Some Name';         opp.StageName = 'Prospect';         opp.CloseDate = Date.today().addDays(30);          MyHelperClass.someMethod(opp);     } }   The above inserts the opportunity and does not trigger an exception. Am I doing something wrong?
69852
So I came across some code this morning that looked like this:  try {     x = SomeThingDangerous();     return x; } catch (Exception ex) {     throw new DangerousException(ex); } finally {     CleanUpDangerousStuff(); }   Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.  My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?
18992
I'm developing an application where I the need to invoke a method of a generic class and I don't care about the instances actual type. Something like the following Java code:  public class Item&lt;T&gt;{   private T item;    public doSomething(){...} }  ... public void processItems(Item&lt;?&gt;[] items){  for(Item&lt;?&gt; item : items)    item.doSomething(); }   At the time I was on a hurry, so I solved my problem by defining a interface with the methods I needed to invoke and made the generic class implement it.  public interface IItem   {    void doSomething(); }  public class Item&lt;T&gt; : IItem {   private T item;    public void doSomething(){...} }  ... public void processItems(IItem[] items) {  foreach(IItem item in items)    item.doSomething(); }   This workaround works fine, but I'd like to know what is the correct way to achieve the same behavior.    EDIT:  I forgot to refer that the caller of processItems doesn't know the actual types. Actually the idea was that the array passed as argument to processItems could contain intermixed types. Since its not possible to have such an array in .Net, using a non generic base class or interface seems to be the only way.
46209
Using instance methods as callbacks for event handlers changes the scope of this from "My instance" to "Whatever just called the callback". So my code looks like this  function MyObject() {   this.doSomething = function() {     ...   }    var self = this   $('#foobar').bind('click', function(){     self.doSomethng()     // this.doSomething() would not work here   }) }   It works, but is that the best way to do it? It looks strange to me.
56738
In Field Service Lightning I have a Trigger on ServiceReport which sends an email with attachment coming from ContentVersion.   This is the Test class I have written.  @isTest  private class testCreateServiceReport{       static testMethod void validateWO() {       WorkOrder wo = new WorkOrder();       wo.subject = 'Testing';       insert wo;       ServiceAppointment sa = new ServiceAppointment();       sa.ParentRecordId = wo.Id;       sa.EarliestStartTime = DateTime.now();       sa.DueDate = DateTime.now();       insert sa;       List&lt;ServiceReportLayout&gt; srl = [Select Id FROM ServiceReportLayout];       ServiceReport sr = new ServiceReport();       sr.ParentId = sa.Id;       sr.Template = srl[0].Id; //Need to check if there is a way to avoid srl[0] notation       insert sr; //If I comment this the text result is pass. When I enable it I get too see the below mentioned error.  }  }   This is the error Methods defined as TestMethod do not support Web service callouts I know that we need to write Test Classes for code that involves web service callouts using setMock() but I dont understand in what way inserting ServiceReport is related to making a callout.  Any help on this will be really helpful.
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
55180
So I have a method that takes as a parameter an Id of a object and uses it to make an external callout.  Unfortunately I can't seem to figure out any way to test it.  @isTest static void sometimes_salesforces_sucks() {    My_Object__c foo = new My_Object__c(Name='test');    insert foo;    MyClient client = new MyClient();    MyMockResponseGenerator mockResponse = new MyMockResponseGenerator();    Test.setMock(HttpCalloutMock.class,mockResponse);     Test.startTest();    client.bar(foo.Id);    Test.stopTest(); }    says that using start/stop test should work, but it doesn't work for me
96847
I have a code sample that gets a SEL from the current object,   SEL callback = @selector(mymethod:parameter2);   And I have a method like    -(void)mymethod:(id)v1 parameter2;(NSString*)v2 { }   Now I need to move mymethod to another object, say myDelegate.  I have tried:  SEL callback = @selector(myDelegate, mymethod:parameter2);   but it won't compile.
33281
In terms of Java, when someone asks:      what is polymorphism?   Would overloading or overriding be an acceptable answer?  I think there is a bit more to it than that.   IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?  I think overloading is not the right answer for sure.
38244
I have a method that's about ten lines of code.  I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code.  This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers.  What's my best alternative?
98970
I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the parent doesn't offer which is in its self not fundamentally sound. But is there some way to do this? Here is a code example to so I can better explain what I"m asking.  public class SomeBaseClass {     public string GetBaseClassName {get;set;}     public bool BooleanEvaluator {get;set;} }  public class SomeDerivedClass : SomeBaseClass {     public void Insert(SqlConnection connection) {           //...random connection stuff           cmd.Parameters["IsItTrue"].Value = this.BooleanEvalutar;           //...     } }  public static void Main(object[] args) {     SomeBaseClass baseClass = new SomeBaseClass();     SomeDerivedClass derClass = (SomeDerivedClass)baseClass;      derClass.Insert(new sqlConnection()); }   I know this seems goofy but is there any way to accomplish something of this sort?
57401
I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called AddressList, containing simple nodes called ListNode). The catch is that everything would have to be done with recursive algorithms. I was able to do everything fine sans one method: public AddressList reverse()      ListNode:    public class ListNode{   public String data;   public ListNode next; }   Right now my reverse function just calls a helper function that takes an argument to allow recursion.  public AddressList reverse(){   return new AddressList(this.reverse(this.head)); }   With my helper function having the signature of private ListNode reverse(ListNode current).  At the moment, I have it working iteratively using a stack, but this is not what the specification requires. I had found an algorithm in C that recursively reversed and converted it to Java code by hand, and it worked, but I had no understanding of it.  Edit: Nevermind, I figured it out in the meantime.  private AddressList reverse(ListNode current, AddressList reversedList){   if(current == null)        return reversedList;   reversedList.addToFront(current.getData());   return this.reverse(current.getNext(), reversedList); }   While I'm here, does anyone see any problems with this route?