It doesn't like 'super' where ever I put it.

B

bilsch

Add nothing; *subtract* "void".

A constructor is a special piece of code that initializes a
brand-new object. It looks superficially like a method, and you
can write the same kinds of Java statements in a constructor as
in a method, but it is not a method at all. Among the differences:

- You can call methods, but you cannot "call" constructors.
Constructors run when a `new' operation is performed, to
set up the new object. There are a few operations that
sort of look like "calls" to constructors -- one constructor
can invoke another constructor of the same class with a
this(...) construct, or a constructor of its superclass
with a super(...) -- but as you've seen you cannot just
"call" a constructor the way you'd call toString().

- Methods have names, but constructors don't. If a
constructor throws an exception and a stack trace gets
printed, you'll see something like "ClassName.<init>" as
a sort of stand-in for the name -- but you quite clearly
can't use "<init>" as the name of a method!

- Constructors have no return type, not even `void'. A method
*always* has a return type, even if it's `void'.

I think you need a Java textbook, just like everyone else did
when starting out.

Thanks for the explanation. I have some Java books. They are kind of
vague on the subject.
 
B

bilsch

"void" is a special return type which denotes "returns nothing." It's
a rule of Java syntax that the declaration of a constructor _must not_
have a return type, while the declaration of a method which _must_
have one.
Thanks.
 
B

bilsch

Constructors are fundamentally different from ordinary methods, so most
object-oriented languages use a different syntax for them. In Java, a
constructor definition looks like a method, but without an explicit
return type and using a name that matches the class name. In other
languages the syntax may be different -- for example, in Python the name
is always __init__ -- but the underlying idea is the same: constructors
are not ordinary methods and take a different syntax.

Why are constructors different? Most classes have some code that you
want to run whenever a new object is created, and it would be tedious to
have to call it explicitly every time. I used to mimic OOP in C and you
had to do things like

struct Foo* foo = (struct Foo*) malloc(sizeof(struct Foo));
foo->init();

Forcing all object creation to go through a constructor makes the code
simpler and more reliable. And even when a class has a constructor that
appears to be empty, there's still some code that the compiler generates
automatically the make the new object a proper instance of its class.
Thanks for the info.
 
M

markspace

Thanks for the explanation. I have some Java books. They are kind of
vague on the subject.


I like to keep in mind lists of books that aren't good Java books, as
well as those that are good, just to be able to recommend them (or not)
when questions are asked on this list. Care to let us know which books
you find wanting?

FYI, I own and recommend Learning Java, published by O'Reilly, third
edition. I don't recall exactly where I learned that constructors have
no return type keyword, but I'm sure it's in there.

I also recommend the Java tutorial on Oracle's website. It's not
in-depth, but it often is useful to answer specific questions.

<http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html>

"Constructor declarations look like method declarations—except that they
use the name of the class and have no return type"
 
L

Lew

bilsch said:
Hello, below is my program stripped to bare bones. Java says 'super' must be
first statement in constructor. I've moved it everywhere still no luck. The
program was running yesterday and I can't figure what could be wrong. Any
suggestions?

The error output is listed below the program

TIA Bill S.


PROGRAM:

import javax.swing.*;
import java.awt.*;
import java.util.*;

public class CalcFrame1 extends JFrame{

public void CalcFrame1() {

Everyone else has told you of the difference a 'void' makes.

You asked where this is taught so you can learn it. The Java tutorial is the
canonical starting place.

<http://docs.oracle.com/javase/tutorial/>
particularly
super("CalcFrame1");
//setTitle("CalcFrame1");
FlowLayout flo = new FlowLayout();
setLayout(flo);
setLookAndFeel();
//setSize(600,600);

JButton shf = new JButton("shft");
JButton chs = new JButton("chs");
add (shf);
add (chs);

pack();
setVisible(true);

Don't 'setVisible()' in the constructor. Constructors, as the name implies,
are for construction of an object, but not its operation.

Let the object finish building itself completely before anything else can get
to it.
}
private void setLookAndFeel(){
try{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception exc){

Don't catch just 'Exception' here, but the exact exceptions you are required
to catch.
// ignore error

And *never* ignore errors!
}
}

public static void main(String[] args){
CalcFrame1 ClFr1 = new CalcFrame1();

Oops. You didn't start this on the EDT (Event Dispatch Thread). (And you don't
let the object finish construction before things can get to it.)

The Swing tutorial (ibid.) explains this a little bit.
 
G

Gavino

Stefan Ram said:
There was no (other) constructor in the code of the OP,
so a default constructor must have been generated, which
will include a correct call of »super()«.

It can't because the superclass (JFrame) does not have a constructor without
arguments.
 
R

Robert Klemme

There was no (other) constructor in the code of the OP,
so a default constructor must have been generated, which
will include a correct call of »super()«.

Only that this won't be done for non constructors which is what the
method was, as has been pointed out
public void CalcFrame1() { ... }

Note that super(...) is always a constructor call because method calls
read super.method(...).

Granted, the error message is probably not the most telling. Eclipse says
Constructor call must be the first statement in a constructor
CalcFrame1.java /c.l.j.p/src line 8 Java Problem

Which is certainly clearer.

Cheers

robert
 
M

Martin Gregorie

()

My apologies.
I don't know where I got that erroneous idea from, but somehow I've been
carrying it around in my head for the last 12 years.
I should have checked the JavaDocs instead of relying on badly
remembered information.

Now I'm equally confused about the wording of the error message.

As Stefan said, I believe its objecting to the call to
super("CalcFrame1") in the class erroneously declared as
"public void CalcFrame1()".
 
D

Daniel Pitts

Hello, below is my program stripped to bare bones. Java says 'super'
must be first statement in constructor. I've moved it everywhere still
no luck. The program was running yesterday and I can't figure what could
be wrong. Any suggestions?

The error output is listed below the program

TIA Bill S.


PROGRAM:

import javax.swing.*;
import java.awt.*;
import java.util.*;

public class CalcFrame1 extends JFrame{

public void CalcFrame1() {
super("CalcFrame1");
//setTitle("CalcFrame1");
FlowLayout flo = new FlowLayout();
setLayout(flo);
setLookAndFeel();
//setSize(600,600);

JButton shf = new JButton("shft");
JButton chs = new JButton("chs");
add (shf);
add (chs);

pack();
setVisible(true);
}
private void setLookAndFeel(){
try{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception exc){
// ignore error
}
}

public static void main(String[] args){
CalcFrame1 ClFr1 = new CalcFrame1();
}
}

ERROR OUTPUT:
java.lang.VerifyError: Constructor must call super() or this() before
return in method CalcFrame1.<init>()V at offset 0
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2442)
at java.lang.Class.getMethod0(Class.java:2685)
at java.lang.Class.getMethod(Class.java:1620)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:492)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:484)
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
This is actually a runtime error, a problem with the .class file. Not
sure how that happened, unless you have a faulty compiler.
 
L

Lew

Martin said:
As Stefan said, I believe its objecting to the call to
super("CalcFrame1") in the class erroneously declared as
"public void CalcFrame1()".

Here's the chain:

The rule for 'super()' constructor calls is that they must appear only as the first line in a constructor. The OP put it in a different place, inside a method, violating the rule stated in the error message:
"Constructor must call super() or this() before return in method CalcFrame1.<init>()V at offset 0"

That's not where the OP's code called 'super()'. Ergo, it violated that rule.
 
E

Eric Sosman

My apologies.
I don't know where I got that erroneous idea from, but somehow I've been carrying it
around in my head for the last 12 years.
I should have checked the JavaDocs instead of relying on badly remembered information.

Now I'm equally confused about the wording of the error message.

You are not the only confused person. It might just be clumsy
wording:

Constructor must call super() or this() before return in
method CalcFrame1.<init>()V [...]

certainly seems to be complaining about a constructor: That's the first
word of the message, and <init> is what one usually sees when a message
tries to mention the "name" of a (nameless) constructor.

The message *seems* to be saying: "The constructor fails to call
super() or this() when it ought to." Instead, what I think it means
is "The super() or this() call should be in a constructor, not in a
method (where it makes no sense)."

One must, however, cut the compiler a certain amount of slack.
There's a built-in ambiguity about diagnosing "the" error in erroneous
source. All the compiler knows for sure is that the source is wrong;
to explain "how" it is wrong, the compiler must guess at what it tried
(and failed) to express. That is, there are many possible compilable
programs at smaller and larger "edit distances" from the incorrect code
at hand, and the compiler has no way to know which was intended. To
describe "the error," the compiler must choose one (or a small family)
of those nearby candidates and describe how the offered code differs.
But it's all guesswork -- even a compilable program may not be what was
intended (that's why we debug...).

The practical lesson is not to take error messages too literally.
Very often the message will highlight the difficulty well enough to
prompt you to a facepalm and a fix. But when the message seems at an
inexplicable tangent to what you think is going on, the best approach
may be to reinterpret "Operand of binary % must be a duodecimal dingle"
as "Something's wrong," and read no more into it than that.
 
S

Stefan Ram

Eric Sosman said:
Constructor must call super() or this() before return in
method CalcFrame1.<init>()V [...] (...)
at hand, and the compiler has no way to know which was intended.

But the above is not a compiler message, but a run-time message.

For a similar situation, I get a compiler message:

|Main.java:31: error: call to super must be first statement in constructor
|public void test(){ super(); }

. (This message does not actually claim that »test« was a
constructor, although one might read it this way.)
 
L

Lew

Stefan said:
Eric said:
Constructor must call super() or this() before return in
method CalcFrame1.<init>()V [...] (...)
at hand, and the compiler has no way to know which was intended.

But the above is not a compiler message, but a run-time message.

Perhaps there was a transcription error in the OP's message when they put
together their otherwise quite serviceable SSCCE.
For a similar situation, I get a compiler message:

|Main.java:31: error: call to super must be first statement in constructor
|public void test(){ super(); }

. (This message does not actually claim that »test« was a
constructor, although one might read it this way.)

Has anyone tried compiling the OP's first example? (I haven't, and won't.)
Perhaps there's a further anomaly in there.
 
J

John B. Matthews

Lew said:
Stefan said:
Eric said:
Constructor must call super() or this() before return in
method CalcFrame1.<init>()V [...] (...)
at hand, and the compiler has no way to know which was intended.

But the above is not a compiler message, but a run-time message.

Perhaps there was a transcription error in the OP's message when they put
together their otherwise quite serviceable SSCCE.
For a similar situation, I get a compiler message:

|Main.java:31: error: call to super must be first statement in constructor
|public void test(){ super(); }

. (This message does not actually claim that »test« was a
constructor, although one might read it this way.)

Has anyone tried compiling the OP's first example? (I haven't, and
won't.) Perhaps there's a further anomaly in there.

bilsch: Summarizing several insightful answers, "Constructor
declarations look like method declarations—except that they use the
name of the class and have no return type [1]."

In addition to reviewing "Initial Threads" [2], also critically examine
your decision to extend JFrame. It may be more convenient to add a
JPanel containing buttons, as suggested in KeyPadPanel [3].

SSCCE:

import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;

public class CalcFrame extends JFrame {

public /* void */ CalcFrame() {
super("CalcFrame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new JButton("Button"));
pack();
setLocationRelativeTo(null);
setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
CalcFrame cf = new CalcFrame();
}
});
}
}

[1] <http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html>
[2] <http://download.oracle.com/javase/tutorial/uiswing/concurrency/initial.html>
[3] <https://sites.google.com/site/drjohnbmatthews/keypad-panel>
 
B

bilsch

bilsch said:
Hello, below is my program stripped to bare bones. Java says 'super'
must be
first statement in constructor. I've moved it everywhere still no
luck. The
program was running yesterday and I can't figure what could be wrong. Any
suggestions?

The error output is listed below the program

TIA Bill S.


PROGRAM:

import javax.swing.*;
import java.awt.*;
import java.util.*;

public class CalcFrame1 extends JFrame{

public void CalcFrame1() {

Everyone else has told you of the difference a 'void' makes.

You asked where this is taught so you can learn it. The Java tutorial is
the canonical starting place.

<http://docs.oracle.com/javase/tutorial/>
particularly
super("CalcFrame1");
//setTitle("CalcFrame1");
FlowLayout flo = new FlowLayout();
setLayout(flo);
setLookAndFeel();
//setSize(600,600);

JButton shf = new JButton("shft");
JButton chs = new JButton("chs");
add (shf);
add (chs);

pack();
setVisible(true);

Don't 'setVisible()' in the constructor. Constructors, as the name
implies, are for construction of an object, but not its operation.

Let the object finish building itself completely before anything else
can get to it.
}
private void setLookAndFeel(){
try{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception exc){

Don't catch just 'Exception' here, but the exact exceptions you are
required to catch.
// ignore error

And *never* ignore errors!
}
}

public static void main(String[] args){
CalcFrame1 ClFr1 = new CalcFrame1();

Oops. You didn't start this on the EDT (Event Dispatch Thread). (And you
don't let the object finish construction before things can get to it.)

The Swing tutorial (ibid.) explains this a little bit.
Thanks for the specific link. I have been reading the tutorials.
 
B

bilsch

I like to keep in mind lists of books that aren't good Java books, as
well as those that are good, just to be able to recommend them (or not)
when questions are asked on this list. Care to let us know which books
you find wanting?

FYI, I own and recommend Learning Java, published by O'Reilly, third
edition. I don't recall exactly where I learned that constructors have
no return type keyword, but I'm sure it's in there.

I also recommend the Java tutorial on Oracle's website. It's not
in-depth, but it often is useful to answer specific questions.

<http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html>

"Constructor declarations look like method declarations—except that they
use the name of the class and have no return type"
Thanks for the link. I've been reading the tutorials.
 
R

Robert Klemme

Stefan said:
Eric said:
Constructor must call super() or this() before return in
method CalcFrame1.<init>()V [...] (...)
at hand, and the compiler has no way to know which was intended.

But the above is not a compiler message, but a run-time message.

Perhaps there was a transcription error in the OP's message when they put
together their otherwise quite serviceable SSCCE.

I rather think the confusion now reached a degree where people loose
sight of compile time and runtime. :)
Has anyone tried compiling the OP's first example? (I haven't, and won't.)
Perhaps there's a further anomaly in there.

Yes, with Eclipse. See my posting from yesterday for Eclipse _compiler_
(and not runtime!) error message. Repeated for convenience:
Granted, the error message is probably not the most telling. Eclipse says
Constructor call must be the first statement in a constructor CalcFrame1.java /c.l.j.p/src line 8 Java Problem

Which is certainly clearer.

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top