Tuesday, March 27, 2012

cannot find symbol. symbol: constructor

This Java code:

class Top 
{
 public Top(String s) { System.out.print("Top"); }
}

public class Bottom extends Top 
{
 public Bottom(String s)
 {
  System.out.print("Bottom"); 
 }
 public static void main(String[] args)
 {
  new Bottom("A");
 }
}


Produces this compile error:

Bottom.java:9: cannot find symbol
symbol  : constructor Top()
location: class Top
 {
 ^
1 error


While this C# code:
using System;
public class Top
{
 public Top(string s) { Console.WriteLine("Top"); }
}

public class Bottom : Top
{
 public Bottom(string s) { Console.WriteLine("Bottom"); }
 public static void Main(string[] args)
 {
  new Bottom("A");
 }
}

Produces this compile error:
Bottom.cs(9,16): error CS1729: The type `Top' does not contain a constructor that takes `0' arguments
Bottom.cs(4,16): (Location of the symbol related to previous error)
Compilation failed: 1 error(s), 0 warnings

Java compile error is a bit confusing though, I'm thinking what's with curly bracket, why Java is pointing to that as the source of error.

The problem on both code is the base class of Bottom(i.e. Top), don't have any parameterless constructor. Deriver(Bottom) need to construct its base class too.

There are two ways to solve that problem, one is to make a parameterless constructor on Top, the second option is to inform the Bottom's constructor to use any of its base class' constructor

On Java:

class Top 
{
 public Top(String s) { System.out.print("Top"); }
}

public class Bottom extends Top 
{
 public Bottom(String s)
 {
  super(s);
  System.out.print("Bottom"); 
 }
 public static void main(String[] args)
 {
  new Bottom("A");
 }
}


On C#, just call the constructor of its base class, on the constructor line itself

using System;
public class Top
{
 public Top(string s) { Console.WriteLine("Top"); }
 
}

public class Bottom : Top
{
 public Bottom(string s) : base(s) { Console.WriteLine("Bottom"); }
 public static void Main(string[] args)
 {
  new Bottom("A");
 }
}

No comments:

Post a Comment