Thursday, December 12, 2013

Published 12/12/2013 by with 0 comment

The constructor ... is not visible

When you invoke the private constructor of a class in another class, you’ll get the error message “The constructor ... is not visible”. And when the private constructor of a super class is invoked from the subclass implicitly or explicitly, you’ll get the following:

Implicit super constructor ... is not visible for default constructor. Must define an explicit constructor.
Implicit super constructor ... is not visible. Must explicitly invoke another constructor.

See an example below:

public class SuperClass
{

       private SuperClass()
       {
              System.out.println("Super class private constructor");
       }
      
       public SuperClass(int n)
       {
              System.out.println("Super class protected constructor");
       }
}

In the above code, the class has two constructors. Access modifier for one is private and another is public. So if you create an instance of this class using the private constructor in another class, you’ll encounter the error.

You cannot write SuperClass  superClassObject = new SuperClass();
You should call other constructors that you can access as per access modifier rule or the other way of instantiating the class (if available in that class). Sometimes such class has some getInstance() like methods.

Again, when you inherit a class that has private default constructor, you have to write your own constructor and invoke a constructor (that is accessible) within your constructor. In such case, if you do not write any constructor in the subclass you’ll get “Implicit super constructor ... is not visible for default constructor. Must define an explicit constructor.”

This happens because when you do not define any constructor, a default constructor is automatically created by the Java compiler and the default constructor invokes the default constructor of the super class. This is how the constructor is invoked implicitly.

See the code below:
//Code1
public class Subclass extends SuperClass
{
      
}
Or
//Code2
public class Subclass extends SuperClass
{

       public Subclass()
       {
             
       }
}

I have not defined any constructor in code1. In code2, I have defined a constructor but have not invoked any constructor explicitly. So the super class default constructor will implicitly be called.

In the code below I have defined a constructor. But still I called the super class default constructor explicitly through “super()”. I’ll encounter the error.

public class Subclass extends SuperClass
{

       public Subclass()
       {
              super();
       }
}

Now the solutions are:
1.      
      We cannot call the private constructor of class from the subclass or other class. You should look the other constructors or the other way of instantiating class.

2.       If the default constructor of a super class is private, you have to write your own constructor in the subclass and explicitly call visible constructors.

For the above scenario, correct coding would be:

public class Subclass extends SuperClass
{

       public Subclass()
       {
              super(10);
       }

}
Read More
    email this       edit

Tuesday, November 26, 2013

Published 11/26/2013 by with 0 comment

java.lang.UnsupportedOperationException at java.util.AbstractList.remove

When you create a java.util.List object from an array using Arrays.asList method and after that if you try to clear or remove the elements from the list you'll get this run time error. The reason is that Arrays.asList method returns a fixed-size list backed by the specified array.

See in the example code below:

int[] myArray = {5,10,15,20};

List intList = Arrays.asList(myArray);

intList.clear();

Or

int[] myArray = {5,10,15,20};

List intList = Arrays.asList(myArray);

for(int i=0;i
{
intList.remove(i);
}

You'll get error from intList.clear() or intList.remove(i) because you cannot remove from a fixed-size array. And also you cannot add any new element in this list.

If you require to copy array elements in a list object and later need to add/delete elements from the list, you can do it in the following way.

  int[] myArray = {5,10,15,20};
List intList = new ArrayList();
System.out.println(intList); // print empty list
//copy the array elements into the list
for(int i=0;i
{
intList.add(myArray[i]);
}
System.out.println(intList); // print list after copying array elements
//You can now add
intList.add(25);
System.out.println(intList); // print list after adding new element
//You can remove
intList.remove(0);
System.out.println(intList); // print list after removing an element
//You can remove all the elements
intList.clear();
System.out.println(intList); // print list after removing all the elements

Below is the output of this sample code:

[]
[5, 10, 15, 20]
[5, 10, 15, 20, 25]
[10, 15, 20, 25]
[]

Read More
    email this       edit
Published 11/26/2013 by with 5 comments

Resource leak: 'scanner' is never closed

If you do not close the java.util.Scanner object after reading data, you can get an warning saying "Resource leak: 'scanner' is never closed".

In the code below see that the Scanner object is closed in a finally block after reading all inputs using the Scanner object.

int number1, number2;

Scanner scanner = new Scanner(System.in);

try
{
System.out.println("Ener the first number");
number1 = scanner.nextInt();
System.out.println("Ener the second number");
number2 = scanner.nextInt();
}
finally
{
scanner.close();
}

Read More
    email this       edit
Published 11/26/2013 by with 0 comment

Dimensions expected after this token / '[' expected

Java error "Dimensions expected after this token" or " '[' expected " can occur while creating array elements or allocating memory using the keyword new. If the square brackets [] are not used properly, you can get this error message.

See the code below:

int myArray[]=new int{10,20,30,40};

Here this is a syntax error. You have to put square brackets [] after new int. To initialize an array the correct code would be:

int myArray[]=new int[]{10,20,30,40};

or just

int myArray[]={10,20,30,40};
Read More
    email this       edit
Published 11/26/2013 by with 0 comment

Cannot invoke length() on the array type

The error message "Cannot invoke length() on the array type" or "cannot find symbol ... method length()" is related with the use of array.

Java array has a built in property length which is a variable, not method. If you put parenthesis () after the array property length, you'll get this error.

See the example below:

int[] number = {5,10,15};

for(int i=0; i<number.length(); i++)
{
    System.out.println(number[i]);
}

Here number.length() is wrong. To resolve the error, remove the parenthesis ().

The correct code:

for(int i=0; i<number.length; i++)
{
    System.out.println(number[i]);
}

Read More
    email this       edit

Friday, May 20, 2011

Published 5/20/2011 by with 2 comments

attempting to use incompatible return type

We may encounter this error message when we override a superclass method in the subclass with a wrong return type in the subclass method. To understand this, let's see the following two classes.

public class SuperClass
{
public double sum(double a,double b)
{
return (a+b);
}
}

public class Subclass extends SuperClass
{
public long sum(double a,double b)
{
return Math.round(a+b);
}
}

In the above example code, the super class method sum has double return type and in the subclass we have overridden this method where return type is long which is not compatible with double.
What should we do now to remove the error? We should either declare the return type of the subclass as double or change the parameter type.

See the correct code of the subclass below:

public class Subclass extends SuperClass
{
public double sum(double a,double b)
{
return Math.round(a+b);
}
public long sum(long a,long b)
{
return (a+b);
}
}


Read More
    email this       edit

Thursday, May 19, 2011

Published 5/19/2011 by with 5 comments

is not abstract and does not override abstract method

See the code below:


import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyFrame extends JFrame implements ActionListener{
private JButton exitButton = new JButton("Exit");
public MyFrame()
{
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(exitButton);
  exitButton.addActionListener(this);
setSize(300,200);
}
}

If this code is compiled, we will see the error "MyFrame is not abstract and does not override abstract method actionPerformed(java.awt.event.ActionEvent) in java.awt.event.ActionListener"

Why? When we implement an interface(ActionListener in this example) or extend an abstract class in a concrete class, we must override the abstract method(s). In the above example we have implemented ActionListener but have not overridden the abstract method actionPerformed.

The correct code of the above is:

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyFrame extends JFrame implements ActionListener
{
private JButton exitButton = new JButton("Exit");
public MyFrame()
{
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(exitButton);
exitButton.addActionListener(this);
setSize(300,200);
}
public void actionPerformed(ActionEvent ae)
{
System.exit(0);
}
}


Sometimes it happens that we override the abstract method with wrong name spelling or wrong signature, then also we see the same error message. Note that Java is a case sensitive language; most often we write the method name with wrong case (example, actionperformed/ActionPerformed instead of actionPerformed) and see this error message.

For implementing an interface or extending an abstract class, we must override all of the abstract methods (if more than one), though we do not need all. For example, if we implement KeyListener we must override each of the three abstract methods keyPressed, keyTyped and keyReleased though we may not need all of them. In that case, method body can be kept blank. Instead of interface, we can use adapter class (if available) to get rid of overriding all abstract methods.

In summary, override the abstract method with correct name spelling and signature to remove the error.
Read More
    email this       edit
Published 5/19/2011 by with 2 comments

attempting to assign weaker access privileges

Java error "attempting to assign weaker access privileges" can happen when we override a superclass method in the subclass if the access modifier is not correctly chosen.

See the sample code below:

public class SuperClass
{
public void display()
{
System.out.println("this is super class");
}
}


public class Subclass extends SuperClass
{
private void display()
{
System.out.println("this is subclass");
}
}

If the above Subclass is compiled the error message will be:
display() in Subclass cannot override display() in SuperClass; attempting to assign weaker access privileges; was public

Let's understand the error message:
The method display has public access in the SuperClass and private access in the Subclass, that means when overriding this method, a weaker access privilege is going to be set (private is weaker access privilege than public).

So we need to know the allowed access modifier in the subclass for method overriding. The table below shows this:


Access modifier in super class method
Allowed access modifier for overriding
private
private, package, protected, public
package
package, protected, public
protected
protected, public
public
public


Read More
    email this       edit
Published 5/19/2011 by with 4 comments

modifier private not allowed here

Java error "modifier private not allowed here" can occur for any of the following reasons:

1. An outer class declared as private like below:
private class OuterClass
{
    //...
}
An outer class only be public or package private not private or protected. So you can write an outer class as below:
public class OuterClass
{
   //...
}
or
class OuterClass
{
   //...
}
This is true for an interface also. An interface can only be public or package not private or protected.


2. An interface method declared as private.

public interface TestInterface
{
   private void method(); // wrong as the interface method is private
}

An interface can contain only public or package private method.

The correct code of the above is:

public interface TestInterface
{
   public void method();
}
or
public interface TestInterface
{
   void method(); // interface method declared as package private
}
Read More
    email this       edit

Tuesday, May 17, 2011

Published 5/17/2011 by with 0 comment

No Persistence provider for EntityManager named

Are you using JPA and getting the error "Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named ..."

You might have used an entity manager as the following code:


public void persist(Object object) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }


And you might have a persistence.xml file as below:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="PersonPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>person.entity.Person</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/persondb"/>
<property name="javax.persistence.jdbc.password" value="mypassword"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
</persistence>


Now see that, this error may happen for any of the following reasons:



1. In the code EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestPU"); TestPU is passed in the method which must be a valid persistence unit name. In the persistence.xml file the name is defined as persistence-unit name="PersonPU". These two names must be same. So to remove the error the correct code will be :

EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersonPU");

2. If the persistence unit name is correctly used but still the error exists, then confirm that the required jar file containing the JPA implementation classes are available in the classpath. Required jar files for the above code are eclipselink-2.0.0.jar and eclipselink-javax.persistence-2.0.jar

Read More

    email this       edit