Why can't I use protected constructors outside the package for this piece of code:  package code; public class Example{     protected Example(){}     ... }   Check.java  package test; public class Check extends Example {   void m1() {      Example ex=new Example(); //compilation error   } }    Why do i get the error even though i have extended the class? Please explain   EDIT:  Compilation error:     The constructor Example() is not visible
414
In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance?
3732
For example:  javac Foo.java Note: Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
81239
I'm a C++ developer - not a java developer, but have to get this code working...  I have 2 public classes that will be used by another product.  I used the package directive in each of the java files.    package com.company.thing;  class MyClass ...   When I try to compile a test app that uses that I add   import com.company.thing.*;   The javac compiler fails with errors about com.company does not exist.  (even if I compile it in the same directory as the class files I just made a package of)  I am sure I am doing something bone-headed and silly.  I've read the  pages and tried to set up a directory structure like /com/company/thing  etc, but either I have totally screwed it all up or am missing something else.  EDIT thanks for the suggestions - I had tried the classpath previously.  It does not help.  I tried compiling   javac -classpath &lt;parent&gt; client.java    and the result is:  package com.company does not exist   I have the code I want to import (the two java files) in \com\company\product.  I compile those fine.  (they contain MyClass) I even made a jar file for them.  I copied the jar file up to the parent directory.  I then did (in the parent directory with the client java file)   javac -cp &lt;jarfile&gt; *.java   the result is:  cannot access MyClass bad class file: MyClass.class(:MyClass.class) class file contains wrong class: com.company.product.MyClass Please remove or make sure it appears in the correct subdirectory of the classpath.   EDIT  I got the client code to compile and run if I used the fully qualified name for MyClass and compiled it in the parent directory.  I am totally confused now.    compiled with no classpath set - just   javac *.java    in the parent directory - and it worked fine.  I can get a test app to compile, but that is not going to cut it when i have to integrate it into the production code.  Still looking for help.  EDIT:  Finally - not sure why it didn't work before - but I cleaned up all the files all over the directory structure and now it works.    Thanks
13904
I'm doing some architectural cleanup that involves moving a bunch of classes into different projects and/or namespaces. Currently I'm moving the files by hand, building, and then manually adding using Foo statements as needed to resolve compilation errors. Anyone know of a smarter way of doing this? (We're a CodeRush and Refactor! shop, but I'd be interested to hear if Resharper has support for this)
92550
I am receiving the following error.     Constructor not defined: [DynamicBatchApex].(String, String, Map, String) (Line: 9, Column: 30)   If you look at my DynamicBatchApex class, I clearly have the constructor outlined.  Also, what are the positives and downsides of using the global header?   global class NumberOfEmailsSchedulable implements Schedulable {       global void execute(SchedulableContext sc)        {      String query1 = 'SELECT accountId accountId, count( Id) result FROM contact WHERE accountid != null GROUP BY accountId';     Map&lt;String, Object&gt; field_value_pairs = new Map&lt;String, Object&gt;{'Number_Of_Contacts__c' =&gt; 0};     DynamicBatchApex batch1     =   new DynamicBatchApex('accountId', 'result', field_value_pairs, query1);       } }   Batch Apex Class  global class DynamicBatchApex implements Database.Batchable&lt;AggregateResult&gt; {  public String sObjectIdKey; public String sObjectResultKey; public Map&lt;String, Object&gt; sObjectFieldsToUpdate; public String query;   global DynamicBatchApex(String arIdKey, String arResultKey, Map&lt;String, Object&gt; field_value_pairs, String fieldName, String soqlQuery )  {       sObjectIdKey            = arIdKey;     sObjectResultKey        = arResultKey;      sObjectFieldsToUpdate   = field_value_pairs;     query                   = soqlQuery; }  global Iterable&lt;AggregateResult&gt; start(Database.BatchableContext BC)  {     return new BulkIterable(query); }  global void execute(Database.BatchableContext BC, List&lt;sObject&gt; scope)  {      DynamicSObjectUpdater sObjectUpdater = new DynamicSObjectUpdater();      for(sObject sObj: scope)     {         AggregateResult ar      = (AggregateResult)sObj;         ID sObjectId            = (ID)ar.get(sObjectIdKey);         Decimal arResult        = (Decimal)ar.get(sObjectResultKey);          sObjectUpdater.getUpdateSObject(sObjectId, sObjectFieldsToUpdate);     }      sObjectUpdater.updateSObjects();   }  global void finish(Database.BatchableContext BC)  {  } }
5986
Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no (due to type erasure), but I'd be interested if anyone can see something I'm missing:  class SomeContainer&lt;E&gt; {     E createContents()     {         return what???     } }   EDIT: It turns out that  could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.  I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's .
19919
I ran into an interesting behavior recently.  It seems that if I override .equals() to take a parameter other than Object, it doesn't get called.  Can anyone explain to me why this is happening?  It seems to violate my understanding of polymorphism in OOP, but maybe I'm missing something.  Here's much simpler code that shows what I'm seeing:  public class MyClass {   private int x;   public MyClass(int n) { x = n; }   public boolean equals(Object o) { return false; }   public boolean equals(MyClass mc) { return x == mc.x; }   public static void main(String[] args) {     List&lt;MyClass&gt; list = new ArrayList&lt;MyClass&gt;();     list.add(new MyClass(3));     System.out.println("Contains 3? " + list.contains(new MyClass(3)));   } }   When this is run, it prints "Contains 3? false".  It looks like the equals(Object) function is called, even though there is another that would work.  By contrast, if I write equals like this the code works as expected:  public boolean equals(Object o) {   if(!(o instanceof MyClass))     return false;   MyClass mc = (MyClass)o;   return x == mc.x; }   Why isn't it figuring out which version of the function to call based on the type of the parameter?
33547
If I have an abstract parent class like this:  abstract class Vehicle {     public Vehicle(Person driver) {         //     } }   and then I create a child class like this:  public class MagicCarpet extends Vehicle {     //this won't compile }   I encounter the following Compile Error:     Error: Parent class has no 0-argument constructor for implicit construction at line ... column ...   Obviously I can explicitly re-declare a constructor on the child class toget it to compile:  public class MagicCarpet extends Vehicle {     public MagicCarpet(Person driver) {         super(driver);     } }   But I feel this isn't DRY. Not sure what's actually going on under the covers here.  How can I get a constructor (other than the implicit 0-argument one) to be inherited by a child class?
79010
Take the following class as an example:  class Sometype {     int someValue;      public Sometype(int someValue)     {         this.someValue = someValue;     } }   I then want to create an instance of this type using reflection:  Type t = typeof(Sometype); object o = Activator.CreateInstance(t);   Normally this will work, however because SomeType has not defined a parameterless constructor, the call to Activator.CreateInstance will throw an exception of type MissingMethodException with the message "No parameterless constructor defined for this object." Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.
39994
Had a conversation with a coworker the other day about this.  There's the obvious using a constructor, but what are the other ways there?
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?
34071
Consider this:  public class TestClass {      private String a;     private String b;      public TestClass()     {     a = "initialized";     }      public void doSomething()     {     String c;          a.notify(); // This is fine     b.notify(); // This is fine - but will end in an exception     c.notify(); // "Local variable c may not have been initialised"     }  }   I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?  Edit: making the members private was my initial intention, and the question still stands...
58422
What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?
36051
class Test {        bool isVal() const {           return isVal;       }    private:        bool isVal; };   On Compiling this file it says      testClass.cpp:9: declaration of `bool   Test::isVal'      testClass.cpp:3: conflicts with   previous declaration `bool   Test::isVal()'   Although the same would work for java   class Test {    private boolean isVal;    public boolean isVal() {       return isVal;   }  }   Why does the compile error occur in C++ not in Java?
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().
32230
I am writing a test class that needs to be instance-agnostic. On some of our instances we have a managed package that affects the outcome of the test, so I need to insert some test data that will be used by that managed package, but I'm worried that if I migrate this test case to instances without that managed package, it will fail when trying to insert this test data for objects that don't exist on that instance.  To make a long question shorter, is there a way to test for the presence or absence of either a specific object or a managed package so I can run this code conditionally?
22377
Some time ago, I came across a piece of code, that used some piece of standard Java functionality to locate the classes that implemented a given interface. I know the functions were hidden in some non-logical place, but they could be used for other classes as the package name implied. Back then I did not need it, so I forgot about it, but now I do, and I can't seem to find the functions again. Where can these functions be found?  Edit: I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.