I'm a Java beginner and I can't understand when I should create an instance of the superclass or subclass. I'm studying some tutorials online and I found a few times something like the following code:  package test;  class ABC{    public void myMethod(){     System.out.println("Overridden Method");    } } public class test extends ABC{     @Override    public void myMethod(){     System.out.println("Overriding Method");    }     public static void main(String args[]){     ABC obj = new test();     obj.myMethod();    } }   Why I should use ABC obj = new test(); instead of test = new test();? If I need a new ABC object wouldn't it make sense to just use ABC obj = new ABC();?  Thank you, sorry for the noobie question.
685
I have seen this mentioned a few times and I am not clear on what it means. When and why would you do this?   I know what interfaces do, but the fact I am not clear on this makes me think I am missing out on using them correctly.   Is it just so if you were to do:  IInterface classRef = new ObjectWhatever()   You could use any class that implements IInterface? When would you need to do that? The only thing I can think of is if you have a method and you are unsure of what object will be passed except for it implementing IInterface. I cannot think how often you would need to do that.   Also, how could you write a method that takes in an object that implements an interface? Is that possible?
17921
One may not always know the Type of an object at compile-time, but may need to create an instance of the Type.    How do you get a new object instance from a Type?
123439
Ok, bear with me guys and girls as I'm learning.  Here's my question.  I can't figure out why I can't override a method from a parent class.  Here's the code from the base class (yes, I pilfered the java code from an OOP book and am trying to rewrite it in C#).  using System;  public class MoodyObject {     protected String getMood()     {         return "moody";     }      public void queryMood()     {         Console.WriteLine("I feel " + getMood() + " today!");     } }   and here are my other 2 objects that inherit the base class (MoodyObject):  using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace ConsoleApplication1 {     public class SadObject: MoodyObject     {         protected String getMood()         {             return "sad";         }          //specialization         public void cry()         {             Console.WriteLine("wah...boohoo");         }     } }   And:  using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace ConsoleApplication1 {     public class HappyObject: MoodyObject     {         protected String getMood()         {             return "happy";         }          public void laugh()         {             Console.WriteLine("hehehehehehe.");         }     } }   and here is my main:  using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {             MoodyObject moodyObject = new MoodyObject();             SadObject sadObject = new SadObject();             HappyObject happyObject = new HappyObject();              Console.WriteLine("How does the moody object feel today?");             moodyObject.queryMood();             Console.WriteLine("");             Console.WriteLine("How does the sad object feel today?");             sadObject.queryMood();             sadObject.cry();             Console.WriteLine("");             Console.WriteLine("How does the happy object feel today?");             happyObject.queryMood();             happyObject.laugh();         }     } }   As you can see, pretty basic stuff, but here's the output:     How does the moody object feel today?   I feel moody today!      How does the sad object feel today? I   feel moody today! wah...boohoo      How does the happy object feel today?   I feel moody today! hehehehehehe.   Press any key to continue . . .   Not as I expected.  I've tried to make the base method virtual and calling override when trying to override it and that just gets me this error "cannot override inherited member 'MoodyObject.getMood()' because it is not marked virtual, abstract, or override".  I also tried it without the virtual and override and it thinks I'm trying to hide the base method.  Again, I'm new to OOP and would appreciate any guidance.  EDITED TO ADD:  I found it!  The MoodyObject.cs was only a "solution item" in the solution explorer as opposed to a "ConsoleApplication1" item.  I dragged it down to where it belonged in the solution explorer and voila!  It works now.  I marked Luc's answer below as the answer because he offered the help I needed to get to where I have it resolved... I'm learning so much here.  It's amazing and you guys and girls are crazy smart!
65868
There's a good discussion of Generics and what they really do behind the scenes over at , so we all know that Vector&lt;int[]&gt; is a vector of integer arrays, and HashTable&lt;String, Person&gt; is a table of whose keys are strings and values Persons.  However, what stumps me is the usage of Class&lt;&gt;.  The java class Class is supposed to also take a template name, (or so I'm being told by the yellow underline in eclipse).  I don't understand what I should put in there.  The whole point of the Class object is when you don't fully have the information about an object, for reflection and such.  Why does it make me specify which class the Class object will hold?  I clearly don't know, or I wouldn't be using the Class object, I would use the specific one.
1612
From what time I've spent with threads in Java, I've found these two ways to write threads:  With implements Runnable:  public class MyRunnable implements Runnable {     public void run() {         //Code     } } //Started with a "new Thread(new MyRunnable()).start()" call   Or, with extends Thread:  public class MyThread extends Thread {     public MyThread() {         super("MyThread");     }     public void run() {         //Code     } } //Started with a "new MyThread().start()" call   Is there any significant difference in these two blocks of code ?
119696
In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.  Suppose that you want create a subclass of OptionParser that overrides only a single method (for example exit()). In Java you can write something like this:  new OptionParser () {      public void exit() {         // body of the method     } };   This piece of code creates a anonymous class that extends OptionParser and override only the exit() method.  There is a similar idiom in Python? Which idiom is used in these circumstances?
26254
The question is in Java why can't I define an abstract static method? for example  abstract class foo {     abstract void bar( ); // &lt;-- this is ok     abstract static void bar2(); //&lt;-- this isn't why? }
80088
When referencing class variables, why do people prepend it with this? I'm not talking about the case when this is used to disambiguate from method parameters, but rather when it seems unnecessary.  Example:  public class Person {             private String name;      public String toString() {         return this.name;     } }   In toString, why not just reference name as name?  return name;   What does this.name buy?   a stackoverflow question whose code has this pre-pending.
30943
I think there must be something subtle going on here that I don't know about. Consider the following:  public class Foo&lt;T&gt; {   private T[] a = (T[]) new Object[5];    public Foo() {     // Add some elements to a   }    public T[] getA() {     return a;   } }   Suppose that your main method contains the following:  Foo&lt;Double&gt; f = new Foo&lt;Double&gt;(); Double[] d = f.getA();   You will get a CastClassException with the message java.lang.Object cannot be cast to java.lang.Double.  Can anyone tell me why? My understanding of ClassCastException is that it is thrown when you try to cast an object to a type that cannot be casted. That is, to a subclass of which it is not an instance (to quote the documentation). e.g.:  Object o = new Double(3.); Double d = (Double) o; // Working cast String s = (String) o; // ClassCastException   And it seems I can do this. If a was just a T instead of an array T[], we can get a and cast it without a problem. Why do arrays break this?  Thanks.
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?
27628
How would you initialise a static Map in Java?  Method one: static initialiser  Method two: instance initialiser (anonymous subclass) or some other method?  What are the pros and cons of each?  Here is an example illustrating the two methods:  import java.util.HashMap; import java.util.Map;  public class Test {     private static final Map&lt;Integer, String&gt; myMap = new HashMap&lt;&gt;();     static {         myMap.put(1, "one");         myMap.put(2, "two");     }      private static final Map&lt;Integer, String&gt; myMap2 = new HashMap&lt;&gt;(){         {             put(1, "one");             put(2, "two");         }     }; }
6639
What's the difference between:  class Child(SomeBaseClass):     def __init__(self):         super(Child, self).__init__()   and:  class Child(SomeBaseClass):     def __init__(self):         SomeBaseClass.__init__(self)   I've seen super being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.
7194
I read about Java's type erasure .  When does type erasure occur? At compile time or runtime? When the class is loaded? When the class is instantiated?  A lot of sites (including the official tutorial mentioned above) say type erasure occurs at compile time. If the type information is completely removed at compile time, how does the JDK check type compatibility when a method using generics is invoked with no type information or wrong type information?  Consider the following example: Say class A has a method, empty(Box&lt;?&nbsp;extends&nbsp;Number&gt;&nbsp;b). We compile A.java and get the class file A.class.  public class A {     public static void empty(Box&lt;? extends Number&gt; b) {} }     public class Box&lt;T&gt; {}   Now we create another class B which invokes the method empty with a non-parameterized argument (raw type): empty(new Box()). If we compile B.java with A.class in the classpath, javac is smart enough to raise a warning. So A.class has some type information stored in it.  public class B {     public static void invoke() {         // java: unchecked method invocation:         //  method empty in class A is applied to given types         //  required: Box&lt;? extends java.lang.Number&gt;         //  found:    Box         // java: unchecked conversion         //  required: Box&lt;? extends java.lang.Number&gt;         //  found:    Box         A.empty(new Box());     } }   My guess would be that type erasure occurs when the class is loaded, but it is just a guess. So when does it happen?
91055
Presuming I have a class named A, and I want to use the decorator design pattern. Correct me if I'm wrong, but for that to work , we'll need to create a decorator class, say ADecorator, which will hold a reference to an A instance, and all the other decorators will extend this to add functionality.  I don't understand why do we have to create a decorator class, instead of using an A instance?
7441
Was there any reason why the designers of Java felt that local variables should not be given a default value? Seriously, if instance variables can be given a default value, then why can't we do the same for local variables?  And it also leads to problems as explained in :     Well this rule is most frustrating when trying to close a resource in a finally block. If I instantiate the resource inside a try, but try to close it within the finally, I get this error. If I move the instantiation outside the try, I get another error stating that a it must be within a try.      Very frustrating.
16612
I have got a template class as follows:  class MyClass&lt;T&gt; {     T field;     public void myMethod()     {        field = new T(); // gives compiler error     } }   How do I create a new instance of T in my class?
5208
The keyword protected grants access to classes in the same package and subclasses ().  Now, every class has java.lang.Object as superclass ().  Hence I conclude that every class may access java.lang.Object's methods even if they are protected.  Take a look at the following example:   public class Testclass {   public Object getOne() throws CloneNotSupportedException {     return this.clone();   }   public Object getTwo() throws CloneNotSupportedException {     return ((Object) this).clone();   } }   While getOne() compiles fine, getTwo() gives   Testclass.java:6: clone() has protected access in java.lang.Object         return ((Object) this).clone();   I neither understand why getTwo() doesn't compile nor what's the difference (regarding the access of java.lang.Objects members) with getOne().