If statements in a constructor...
Can I just add if statements into a constructor the same way I would put them in a method? Or do I have to do something special to them?
using if's is perfectly fine.
if you object can't live with a value being negative, use if to test for it, and either
1) change it to a valid value if it is
or
2) throw an exception if that is not possible, or does not make sense.
Similar Messages
-
Super- first statement in constructor.
my compiler (Jcreator LE) doesn't seem to recognize that super is the first statement in the constructor, and gives me an error message (the same thing happens using the this keyword).
public void Student(String str, int day, int mo, int yr, String maj)
super(str,day,mo,yr);
major=maj;
return;
With that code as the constructor, I get this error message
C:\Java\JCreator le\MyProjects\Lab 5\Student.java:8: call to super must be first statement in constructor
super(str,day,mo,yr);
If anybody has any ideas why this is happening or what I can do to correct it, I would appreciate it.
Thanks,
GarethYou are trying to call a method.
Instead you have to use super( ) to controll the construction
of a parent class part of an object.
Code is something like this:
class Student {
public Student(String str) {
// initialize this object using str
public Student(int day) {
// initialize this object using day
class FromStudent extends Student {
public FromStudent(String str) {
// pass control to Student constructor
super(str); // the first constructor here
public FromStudent(int day) {
// pass FromStudent to Student constructor
super(day); // the first constructor here -
How we can intiallize the object state
how we can intialize the object state without using constructor or getter setter method?
is their is any way to intialize the state of object using encapsulation??GouravBansal wrote:
how we can intialize the object stateUsing the constructor.
without using constructor You could also use an instance initializer. That's probably what the interviewer was getting at.
or getter setter method?Once you call a getter/setter method, you're past initialization and are actively modifying the state post-initialization.
is their is any way to intialize the state of object using encapsulation??As noted, this makes no sense. Encapsulation is the practice of maintaining the state purely through methods, constructors, and initializers of a class, in as limited and traceable a way as possible. -
Is it possible to throw an exception in a constructor?
I have a constructor that calls its super contructor, but I want to check its variable before passing a variable to the super contructor.
Something like:
public FlatPanelTV(int inches)
super(inches);
How can I check "inches" before passing it to the super(), when the super has to be the first statement of a constructor?
Any help would be great!
ThanksHi! Its me Ronillo.
Yes it is possible. The validation must be after invoking the superclass constructor or let the superclass validates it. For example:
* @(#)NegativeInchException.java 05/06/15
package com.yahoo.ronilloang.demo;
* The runtime exception that is thrown by <code>InchBean</code>.
* @see InchBean
* @author Ronillo Ang
public final class NegativeInchException extends RuntimeException{
* Construct a new NegativeInchException with null as its detail message.
public NegativeInchException(){
super();
* Construct a new NegativeInchException with the specified detail message.
* @param message the detail message.
public NegativeInchException(String message){
super(message);
* @(#)InchNotSetException.java 05/16/15
package com.yahoo.ronilloang.demo;
* The runtime exception that is thrown by <code>InchBean</code>.
* @see InchBean
* @author Ronillo Ang
public final class InchNotSetException extends RuntimeException{
* Construct a new InchNotSetException with null as its detail message.
public InchNotSetException(){
super();
* Construct a new InchNotSetException with the specified detail message.
* @param message the detail message.
public InchNotSetException(String message){
super(message);
* @(#)InchBean.java 05/06/15
package com.yahoo.ronilloang.demo;
* A java bean for storing and retrieving an inch.
* @author Ronillo Ang
public class InchBean{
private int inch; // as it name implies, this is the inch.
* Construct a new empty InchBean.
public InchBean(){
this(0);
* Construct a new InchBean with the specified inch.
* @param inch the inch to be store. Must be 0 and up.
* @throws NegativeInchException when param inch is less than 0.
public InchBean(int inch){
setInch(inch);
* This method is use to set the inch. This will set the new inch if<br>
* <ul>
* <li> The new inch is not less than 0.
* <li> The current inch is not equal to the new inch.
* </ul>
* @param inch the new inch must be 0 and up.
* @throws NegativeInchException when param inch is less than 0.
public void setInch(int inch){
if(inch < 0)
throw new NegativeInchException("Inch Bean");
if(this.inch != inch)
this.inch = inch;
* This method is use to retrieve the current inch. This method will return the current inch if
* and only if the current inch is not 0.
* @throws InchNotSetException when the inch is not set or the current inch value is 0.
* @return the current inch.
public int getInch(){
if(inch <= 0)
throw new InchNotSetException("Inch Bean: Unable to get inch");
return inch;
* @(#)SubInchBean.java 05/06/15
package com.yahoo.ronilloang.demo;
* An abstract subclass of <code>InchBean</code>.
* @see InchBean
* @author Ronillo Ang
public abstract class SubInchBean extends InchBean{
* Construct a new empty SubInchBean.
public SubInchBean(){
this(0);
* Construct a new SubInchBean with the specified inch.
* @param inch the inch to be store. Must be 0 and up.
* @throws NegativeInchException when param inch is less than 0.
public SubInchBean(int inch){
super(inch);
* Use to store this bean into an XML file.
* @return 0 if successful, -1 if not.
abstract public int storeToXML();
* Use to store the specified <code>InchBean</code> into an XML file.
* @param inchBean the bean to be store.
* @return 0 if successful, -1 if not.
abstract public int storeToXML(InchBean inchBean);
}I hope it helps. Take care and God bless you ^_^ -
Passing array of parameters to constructor
I'm writing a script which facilitates interaction between javascript and an already existing flash library. One of the things I need to do is create an instance of class x, where class x can be one of a large number of classes. The constructors for these classes each take different numbers of parameters. I want to pass the parameters in from Javascript as an array, and I was hoping that there would be a way to pass the array contents into the constructor as parameters. I tried using apply, but it's not available on constructors.
The only other option I know of is to write a large case statement full of constructors, and for each parameter pass an integer indexed array element. Is there any other way?Your going to have to unpack your array no matter what, so no.
You can make your class factory with your huge case, or, if you have the source for your lib you could modify the constructor, but its the same amount of work:
Was:
public function MyClass(s:String, n:Number, d:Date){...}
To:
public function MyClass(s:*, n:Number=0, d:Date=nul){
<case code here>
If you have a decent platform, or even javascript, you could maybe think about writing a parser that will generate the class factory case based on the constructor signatures. -
Creating new Connections/Statements/ResultSets
Hi,
RDMS = Sybase
JDBC = Jconnect 5.5 obtained from Sybase website
Purpose:
To loop through the program below with different queries and produce
a resultset.
Details:
I have a program that creates a query stores it in a static setter.
The program calls the program below. The program below:
(1) obtains the query from a static getter
(2) creates a connection/statement/resultset
(3) returns to the calling program where
(a) resultset is displayed
(b) calls close() in the program below which closes the
connection/statement/resultset
Problem:
I thought that creating a new connection/statement/resultset
each time the program below is called would work.
The program below returns the correct resultset for the first query
but when called with a different query returns the first resultset that
was generated.
Question:
Do I have to use different objects for the connection/statement/resultset each time the program is called
even though the existing connection/statement/resultset is closed
before a new connection/statement/resultset is created ?
if yes,
I don't how to change the object for connection/statement/resultset
dynamically each time the program below is called.
Any assistance provided would be greatly appreciated !!
Thanks for your time,
YAM-SSM
package ecmutl;
import java.awt.*;
import java.sql.*;
public class DbConnect implements Runnable {
public static Thread queryThread = null;
public static Font fntF;
public static Connection conn = null;
public static ResultSet rs = null;
public static Statement stmt = null;
public static String nodename = EcmUtlLogicals.getNodeName();
public static String password = EcmUtlLogicals.getPassword();
public String newline = "\n";
public static String sqlstate;
public static String message;
public static String queryThreadDone = "false";
public static String query = EcmUtlLogicals.getQuery();
public static String dbname = EcmUtlLogicals.dbname;
public static String username = EcmUtlLogicals.username;
public static int SybaseReturnCode;
void Connect() {
try {
Class.forName("com.sybase.jdbc2.jdbc.SybDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sybase:Tds:"+nodename+"/"+dbname,username,password);
catch (SQLException exc) {
sqlstate = exc.getSQLState();
message = exc.getMessage();
SybaseReturnCode = exc.getErrorCode();
catch (InstantiationException iste) {
catch (ClassNotFoundException cnfe) {
catch (IllegalAccessException iae) {
if (queryThread == null) {
queryThread = new Thread(this, "Query");
queryThread.start();
} // close if
} // close Connect method
public void run() {
try {
stmt = DbConnect.conn.createStatement();
rs = stmt.executeQuery(query);
queryThread = null;
} // close try
catch (SQLException sqlex) {
sqlstate = sqlex.getSQLState();
message = sqlex.getMessage();
SybaseReturnCode = sqlex.getErrorCode();
queryThread = null;
} // close catch
catch (java.lang.Exception ex) {
ex.printStackTrace ();
} // close catch
queryThreadDone = "true";
} // close run method
static void close() {
try {
if ( rs != null){
rs.close();
if ( stmt != null){
stmt.close();
if ( conn != null){
conn.close();
} // close try
catch (SQLException error){
}// close close()
} // close DbConnect classThen I'd say you should write a QueryThread object
that extends Thread and takes an SQL statement in its
constructor. In the run method, create a connection,
statement, and result set to run that query, close
them in reverse order when you're done, and provide a
getter to give access to the results. Don't return a
reference to the result set; put the results in a data
structure or CachedRowSet and close out the result set
as soon as you're done with it. ResultSets are
database cursors, which are scarce resources.
With this design, every thread has its own connection
and resources. They can't conflict with each other. -
MODHi MOD,
I finished coding a QueryThread object exactly as you instructed
and IT WORKS !!!!! The calling program calls QueryThread by:
QueryThread qt = new QueryThread(query);
qt.start();
QueryThread code:
package ecmutl;
import java.awt.*;
import java.sql.*;
import java.util.List;
import java.util.*;
public class QueryThread extends Thread {
public static Thread queryThread = null;
public static Font fntF;
public static Connection conn = null;
public static ResultSet rs = null;
public static Statement stmt = null;
public static String nodename = EcmUtlLogicals.getNodeName();
public static String password = EcmUtlLogicals.getPassword();
public String newline = "\n";
public static String sqlstate;
public static String message;
public static String queryThreadDone = "false";
public String query;
public static String dbname = EcmUtlLogicals.dbname;
public static String username = EcmUtlLogicals.username;
public static int SybaseReturnCode;
public QueryThread(String query) {
this.query = query;
public void run() {
try {
Class.forName("com.sybase.jdbc2.jdbc.SybDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sybase:Tds:"+nodename+"/"+dbname,username,password);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
List resultSetArray = new LinkedList();
resultSetArray = new ArrayList();
if (rs != null) {
int i;
ResultSetMetaData rsmd = rs.getMetaData ();
int numCols = rsmd.getColumnCount ();
for (i=1; i<=numCols; i++) {
if (i > 1) resultSetArray.add(",");
resultSetArray.add(rsmd.getColumnLabel(i));
resultSetArray.add(newline);
boolean more = rs.next ();
while (more) {
for (i=1; i<=numCols; i++) {
if (i > 1) resultSetArray.add(",");
resultSetArray.add(rs.getString(i));
resultSetArray.add(newline);
more = rs.next ();
EcmUtlLogicals.setResultSetArray(resultSetArray);
if (rs != null){
rs.close();
if (stmt != null) {
stmt.close();
if (conn != null) {
conn.close();
queryThread = null;
catch (SQLException sqlex) {
sqlstate = sqlex.getSQLState();
message = sqlex.getMessage();
SybaseReturnCode = sqlex.getErrorCode();
queryThread = null;
catch (java.lang.Exception ex) {
ex.printStackTrace ();
queryThreadDone = "true";
}I have only be using Java for three months. Sometimes one needs a teacher to go along with the APIs.
Thanks for your patience/help/time
YAM-SSM -
Constructor of class A instantiating class B and vice versa
Hi folks,
I have two classes, namely ZCL_EMPLOYEE and ZCL_USER.
ZCL_EMPLOYEE has an attribute USER type ref to ZCL_USER, populated by a "create object" statement in the constructor method.
ZCL_USER has an attribute EMPLOYEE type ref to ZCL_EMPLOYEE, also populated by a "create object" statement in the constructor method.
Thus when I instantiate one of the classes, this inevitably results in an endless loop.
Is there any way to avoid this? I guess it must be possible to catch already instanciated objects and re-use them rather than instantiating all the time, but how?
Thanks a lot for your help,
PatrickHello Patrick
Since you need to create a couple of instance at the same time this is a task I would solve with the FACTORY pattern, e.g.:
Both class contain static factory methods and the instantiation is set private as suggested by Matthew, e.g.:
DATA:
lo_user TYPE REF TO zcl_user,
lo_empl TYPE REF TO zcl_employee.
lo_user = zcl_user=>create( id_uname = <username> ).
lo_empl = zcl_employee=>create( id_pernr = <personnel number> ).
CREATE method of ZCL_USER:
METHOD create.
CREATE OBJECT ro_instance " of TYPE REF zcl_user
EXPORTING
id_uname = id_uname
* io_employee = " optional parameter for employee instance
ENDMETHOD.
CREATE method of ZCL_EMPLOYEE:
METHOD create.
CREATE OBJECT ro_instance " of TYPE REF zcl_employee
EXPORTING
id_pernr = id_pernr
* io_user = " optional parameter for user instance
ENDMETHOD.
CONSTRUCTOR method of ZCL_USER:
METHOD constructor.
IF ( io_employee IS BOUND ).
me->mo_employee = io_employee.
ELSE.
" get PERNR via infotype 0105
CREATE OBJECT me->mo_employee
EXPORTING
id_pernr = <personnel number>
io_user = me.
ENDIF.
ENDMETHOD.
CONSTRUCTOR method of ZCL_EMPLOYEE:
METHOD constructor.
IF ( io_user IS BOUND ).
me->mo_user = io_user.
ELSE.
" get uname via infotype 0105
CREATE OBJECT me->mo_user
EXPORTING
id_uname = <username>
io_employee = me.
ENDIF.
ENDMETHOD.
Final remark: If you are not yet aware of class CL_PT_EMPLOYEE you may want to have a look at my Wiki posting
[Unified Access to All HR Infotypes|https://wiki.sdn.sap.com/wiki/display/Snippets/UnifiedAccesstoAllHR+Infotypes]
Regards
Uwe -
Hi,
I have come across following piece of code.
Public class A {
/* Some variables */
public A(){
super();
}Here, I don't understand why "super()" is used although class A is not extending any other class (forget Object class)!!
Any thoughts?
Thanks in advance,
Arun> Here, I don't understand why "super()" is used
although class A is not extending any other
class (forget Object class)!!
It's a bit extraneous; the compiler will insert a call to super() automagically. This applies to every constructor, whether the class extends something other than java.lang.Object or not.
Constructor rules:
1) Every class has at least one constructor.
1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg constructor. In this case, you must explicitly define a public MyClass() {...} if you want one.
1.3) Constructors are not inherited.
2) The first statement in the body of any constructor is either a call to a superclass constructor super(...) or a call to another constructor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a constructor that you define, then the compiler implicitly inserts a call to super's no-arg constructor super() as the first call. The implicitly called constructor is always super's no-arg constructor, regardless of whether the currently running constructor takes args.
2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.
~ -
Invoked super class constructor means create an object of it?
Hei,
i have create one class that extends another class. when i am creating an object of sub class it invoked the constructor of the super class. thats okay.
but my question is :
constructor is invoked when class is intitiated means when we create an
object of sub class it automatically create an object of super class. so means every time it create super class object.Hi,
An object has the fields of its own class plus all fields of its parent class, grandparent class, all the way up to the root class Object. It's necessary to initialize all fields, therefore all constructors must be called! The Java compiler automatically inserts the necessary constructor calls in the process of constructor chaining, or you can do it explicitly.
The Java compiler inserts a call to the parent constructor (super) if you don't have a constructor call as the first statement of you constructor.
Normally, you won't need to call the constructor for your parent class because it's automatically generated, but there are two cases where this is necessary.
1. You want to call a parent constructor which has parameters (the automatically generated super constructor call has no parameters).
2. There is no parameterless parent constructor because only constructors with parameters are defined in the parent class.
I hope your query is resolved. If not please let me know.
Thanks & Regards,
Charan. -
Call to super must be first statement
I'm new to Java and I have a question regarding super(). I'm implementing a design where we have a custom exception which extends Exception. The design calls for null messages to lead to throwing an IllegalArgumentException, but Exception's constructor does not throw an IllegalArgumentException for a null message.
Here is what I want to do, but not allowed to since super must be the first statement in the constructor:
public CustomException(String message) {
if (message == null) {
throw new IllegalArgumentException("message cannot be null.");
super(message);
}I could call super first and then throw an exception if the message is null, but that doesn't seem like a good solution.public CustomException(String message) {
super(nullCheck(message));
static String nullCheck(String message) {
if (message == null) {
throw new IllegalArgumentException("message cannot be null.");
return message;
} -
Overloading constructor question
The following douse not seem to work:-
class A {
A( int i ) {
System.out.println( "A constructor" + i );
class B {
B( int i ) {
System.out.println( "B constructor" + i );
class C extends A {
C () { // line 17
System.out.println( "C constructor" );
public static void main( String[] args ) {
C c = new C();
It complaines at line 17
A(int) in A cannot be applied to ()
C () {
^
This has totaly bafeld be. I thought it was OK to add overloaded constructors in inheratid classes but it seems to be complaining that I am replacing C(int) wit C(), i.e. the constructor in the subclass has diferent arguments. surly this should simply add an overloaded constructer?
BenThe first statement in every constructor must be a call to either a) another constructor in that class or b) a constructor of the super class. If you do not specify a call to either, then the compiler automatically will insert a call to the no argument constructor of the super class. Since there isn't a no-arg constructor in A, the compiler complains that you are calling the A(int) constructor with no arguments. You need to either add a no argument constructor to A, or you need to call the A(int) constructor from the C constructor with some default value.
In case you didn't know, to call a super constructor from a subclass, you use the super keyword.
Example:
class A {
A(int i) {}
class B extends A {
B() {
super(2); //This call the A(int) constructor.
} -
This() and super() invocations in constructor bodies
Hi,
Could someone please explain why it is not allowed to explicitly
call this() or super() in a constructor body anywhere as opposed
to the first statement in the constructor (which in turn implies that
this() and super() can not be used together) ?
Also, If the constructor is a constructor for an enum type, it is a compile-time
error for it to invoke the superclass constructor explicitly. Why ?
And the last question - why it is not allowed to invoke this() or super()
with instance fields ?
Cheers,
AdrianAdrianSosialik wrote:
Could someone please explain why it is not allowed to explicitly
call this() or super() in a constructor body anywhere as opposed
to the first statement in the constructorI think it was a language design decision. One could allow certain statements before invoking another constructor, but this would probably cause more confusion than help. So I guess it was deliberatly chosen to not allow this.
(which in turn implies that this() and super() can not be used
together) ?Yes, but if this would be permitted, it would also be harder to guarantee that a superclass constructor gets called exactly once.
Also, If the constructor is a constructor for an enum type,
it is a compile-time error for it to invoke the superclass
constructor explicitly. Why ?Could you provide a "compilable" code snippet that demonstrates this?
And the last question - why it is not allowed to invoke this()
or super() with instance fields ?As you are not able to store something in them before the invocation, they contain their default values... (the JVM allows storing values in instance fields before invoking another constructor, but it was apparently decided to not include such a thing in Java) -
Super with This in same constructor
Hi All,
I tried to use Super and this keyword in same constructor but it is not working.It gives the exception like constructor call must be the first. I know in base class's constructor super class's constructor should be first statement but also can we not use same class's constructor as second statement in the constructor.?
Thnkxcan we not use same class's constructor as second statement in the constructor.?No.
See the Constructor Rules, reply 2 here: http://forum.java.sun.com/thread.jspa?threadID=721402&messageID=4161149 Your question is covered in point 2. -
Where and when to prepare your statement
I would like to know some others opinion on the following question. Is it better practice to prepare your statements in the constructor, so that they only need to be prepared once, or is it better to prepare them in the methods where they are actually being used and then close them in a finally block in that method?
On one side you have a speed improvement and on the other you have better readability and you are closing all your resources properly.
I am interested in hearing others opinions on this matter.
thanks........I would like to know some others opinion on the
following question. Is it better practice to prepare
your statements in the constructor, so that they only
need to be prepared once, or is it better to prepare
them in the methods where they are actually being
used and then close them in a finally block in that
method?The latter.
On one side you have a speed improvement and on the
other you have better readability and you are closing
all your resources properly.The speed improvement will almost certainly be negligible compared to the time to actually execute the query and process the results. I wouldn't worry about that paritcular optimization unless and until I measured a real bottleneck there. -
Abstract classes having constructors?
InputStream is an abstract class. But then according to API it has a public constructor. Well, since it cannot be instantiated, why does it need to have a constructor? What's the point? Thanks!
I don't know why it would have a public constructor, but it definitely needs at least one c'tor. Usually abstract classes' c'tors are protected.
A constructor does not create an object, it only initializes an already created object to a valid initial state. When creating an instance of a subclass, the ancestors' constructors, starting with Object, are run first, before the descendants'. This way a child knows that the "parent portion" of the object is in a valid state before its constructor starts.
Constructor rules:
1) Every class has at least one ctor.
1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
1.3) Constructors are not inherited.
2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.
Maybe you are looking for
-
Recently Changed Items web part line spacing
I have this web part setup and it looks great except that it has extra space between each line. The options for changing this in the web part properties are: Diagnostic Large Picture Two Lines Videos (the other options include pictures)
-
Canon d1320 I can't print or scan from my computer
I have Canon D1320. the problem I can't print or scan from my computer until i choose the printer mode first. and then i print or scan from my computer
-
Pantone Color 5615 Coated Won't Print On 1 of 2 Identical HP DesignJet 5500s
Hi, We've run into an odd problem where we have 2 locations with identical setups: Creative Suite Design Premium 4, Mac Pros, and HP DesignJet 5500s. The same InDesign file prints fine in one location with a DesignJet 5500, but when we print the sam
-
Exit_saplrsbbs_002
Hi all, What is the purpose of user exit <b>Exit_saplrsbbs_002</b>. I read somewhere it is called before jump into R/3. Please let me know role of this user exit. Thanks and Regards Satish
-
Is it possible to download only ONE MONTH of a calendar into iCal
I have downloaded an ocean tides calendar for a trip. I only need the data for certain dates, but I have about 8 entries per day for the whole year. I know I can turn the ocean tides calendar on or off, but I would prefer limiting the number of days