My constructor method is bogged!
Hi There,
I've got some problems with constructor methods in my program, of course the constructors look fine to me, but then faulty code usually looks good to any programmer after enough hours! Here is some of my code, firstly the following snippet shows the objects being instantiated.
public static ButtonData BtData1;
public static ButtonData BtData2;
public static ButtonData BtData3;
public static ButtonData BtData4;
public static ButtonData BtData5;
public static void main(String[] args)
try{
inStream = new FileInputStream("ObjStore");
objStreamIn = new ObjectInputStream(inStream);
if(objStreamIn.available() == 0)
objStreamIn.close();
inStream.close();
BtData1 = new ButtonData("Link1",null);
BtData2 = new ButtonData("Link2",null);
BtData3 = new ButtonData("Link3",null);
BtData4 = new ButtonData("Link4","Zero");
BtData5 = new ButtonData("Link5","Zero");
else
}catch(IOException e){}
GUI xyz = new GUI();
}Alot of the above code is related to serialization -- mainly checking to see whether or not objects already exist on file, and if they do not, instantiating them. Notice that the above constructors have different parameters or arguments (I can't remember which word describes it best!) -- it doesn't seem to matter whether I use two strings such as ("Link4","Zero") or ("Link1",null) -- both create errors. The class that is instantiated looks like this:
import java.io.*;
public class ButtonData implements Serializable
String Name;
String Path;
ButtonData(String Name,String Path)
this.Name = Name;
this.Path = Path;
protected String getName()
return Name;
protected String getPath()
return Path;
protected void setName()
Name = Begin.LinkName.getText();
protected void setPath()
Path = Begin.ExecT.getText();
}As far as I can tell the constructor above follows all the relevant syntax rules, as does the first snippet of code that I provided -- where the objects are instantiated. I will probably feel like a real meat head if I have done something dump and obvious, however I have double checked the code and it looks fine to me. When trying to compile the code I get the following error messages (using JBuilder7) -- these error messages highlight the relevant sections of the first code snippet I provided:
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 61, column 23
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 62, column 23
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 63, column 23
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 64, column 23
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 65, column 23If anybody can shed some light on what is going on here it will be greatly appreciated.
Thanks
Thanks everybody for your kind constributions, unfortunately I have tried all suggestion provided and have come up with naught. As both classes are in the same package, the question of scope is resolved, and making the ButtonData objects constructor public has no effect on the error messages displayed. I have also modified the ButtonData class so that accessor and mutator methods are public and variables are private, unfortunately this also has had no effect on the immediate error messages. If anybody has further suggestions they will be greatly appreciated. I thought perhaps that the issue with the constructor may be related to the implementation of the serializalbe interface ----->
beyond that idea I am seriously stuck!
Similar Messages
-
Declaring constructor method public or private. What's the point?
My book declares the constructor method public. I tried declaring it private, and without any modifier out of curiousity. It runs exactly the same. What's the point of doing so?
public class test
public static void main( String[] args )
test fun = new test();
test fun2 = new test(2);
System.out.println( fun );
// System.out.println( test.toString() );
public String toString()
return "This is the toString";
test()
System.out.println( "This is the constructor method" );
test( int x )
System.out.println( "This is the constructor method: " +x );
}yougene wrote:
I'm new to OOP so maybe I'm not completely grasping the terminology. But this program works just fine with my class.
public class test2
public static void main( String[] args )
test foo = new test();
}It gives me the following output
----jGRASP exec: java test2
This is the constructor method
----jGRASP: operation complete.The constructor method is executing from an outside class. I tried this with and without the private modifier on the constructor. Same result.Try compiling this.
public class C1 {
private C1() {
System.out.println("C1 c'tor");
public class C2 {
public void foo() {
C1 c1 = new C1();
} -
I'm not sure how to handle the behaviour of a constructor method.
I have a constructor in a class that calls native function via jni to initialize a device. If native function call fails for some reason, I make it throw an exception (NativeFailureException which I defined).
But I'm not sure how to handle that correctly in my constructor. Should I declare constructor method so that it throws (then propagates) the same exception to the user of my object, or should I handle internally the exception and maybe block the execution of the code? (if device fails to initalize, the class is useless).
Because if i declare the constructor so that it throws the exception, then every time one use my class has to place the creation of the object in a try ... catch statement and that seems not so neat to me ... what do you think?The class will be useless since it provides an interface to the underlying c driver to the device. If the device can't be initialized by the driver, then all its methods are useless since I can't even initalize the communication between my java class and the device, via the native driver.
But the problem is, if I catch the exception in the constructor I may have a code like this:
Class NativeDriverTest{
main{
NativeDriver myDriver;
try{
myDriver = new NativeDriver();
}catch (Exception e){
System.out.println ("OMG! " + e.toString());
System.Exit(1);
myDriver.func(...);
}But if I try to compile the code I get an error on myDriver.func(...) call
variable myDriver might not have been initialized
Why is that an error and not rather a warning? I know that the variable "might not have been initialized" but it's my work to ensure that this doesn't happen ... why it doesn't compile?
Should I put all my myDriver calls in the try block?
Should I use another syntax? -
Constructor method, Can you easily solve the issue?
I have had many problems intergrating a constructor method into my program. This is my first time programming in java, can someone please help me. I have contructed a class for an airplanelisttester, that allows the user choice to add or remove planes from the program using a switch method, i have yet to program each "case" accordingly, but i am having trouble at the start of the code. I need to create an "airplanelist" object, i have found some help on the internet, but i am not sure what is going wrong.
public class AirplaneListTester
public static void main (String[] args)
throws java.io.IOException
char choice;
int size;
size = EasyIn.getint();
AirplaneList plane = new AirplaneList();
plane.add(Airplane) = "Add a plane?";
plane.remove(int) = "Remove a plane?";
plane.isEmpty() = "Is Empty";
plane.isFull() = "Is Full";
plane.getitem(int) = "Airplanenumber";
plane.getTotal() = "size" ;
public AirplaneList
private boolean add(Airplane);
private boolean remove(int);
private boolean isEmpty();
private boolean isFull();
private int getitem(int);
private int getTotal();
//..............rest of the program using swtich comands to alow the user to add\remove an airplane , check if a list is empty or //full and display the list as well as exit the program.
}ok so it should look a little like this? I am not really sure, on how to create these objects? ;-<. I understand that "isEmpty" and "isFull" should bounce back very obvious boolean statements, i.e. isfull or isempty. However I am not sure on what values to initiate for "add(Airplane)" ? Is that null? or should i prompt the user to enter one?
import javax.swing.JOptionPane;
public class AirplaneList
public static void main (String[] args)
throws java.io.IOException
char choice;
int size;
size = EasyIn.getint();
AirplaneList plane = new AirplaneList();
plane.add(Airplane) = "Add a plane?";
plane.remove(int) = "Remove a plane?";
plane.isEmpty() = "Is Empty";
plane.isFull() = "Is Full";
plane.getitem(int) = "Airplanenumber";
plane.getTotal() = "size" ;
//declaration
private boolean add(Airplane);
private boolean remove(int);
private boolean isEmpty;
private boolean isFull;
private int getitem(int);
private int getTotal;
//constuctor
public AirPlaneList
add(Airplane) = null;
remove(int) = null;
isEmpty = true;
isfull = false;
getitem(int) = size;
getTotal = null; //initialisation
//methods
public boolean isFull()
return isfull;
public boolean isEmpty()
return isEmpty;
//..............rest of the program using swtich comands to alow the user to add\remove an airplane , check if a list is empty or
//full and display the list as well as exit the program.
} -
Constructor Method parameter problem
I write my class whit this constructor method.
public Immobile(int id, String complesso, String tipoed,double prezzo) {
this.id = id;
this.complesso = complesso;
this.tipoed =tipoed;
this.prezzo = prezzo;
in my app i want to create an object of Immobile class:
Immobile imm = new Immobile(1,"nuovo",null,2);
Always is ok
if I don't want to pass the String parameter I set it whit null.
But if I don't want to pass an integer like first parameter, or double like prezzo parameter, How can I do this?
I don't want to use Overloading of method because if the Immobile class have for example 30 parameter, i don't want to write 30 constructor method.
There is any possibility?I think that my design is ok.Two competent developers and me disagree with you.Sign me in here. Every time I get code with methods with more than 4 parameters I shudder.
A class with 30 constructor parameters is probably a class with 30 fields and more often than not those class fields can be refactored in smaller classes, like ...
I think that made a class User whit parameter Name,
Surname, address, telefon, fax is ok
and i think that a user probably haven't a fax.
I think that one way can be to use all the parameter
like String, that accept null, next, casting orsome
conversion before insert in a database
What do you think about this?Surname, address, telephone and fax give you 30
variables? What are you doing, show a small piece of
relevant code....
class ContactInfo class for tel, fax, mail, pager.
class Adress for City, street, country, etc.
and so on.
I don't know if BiggDaddy 's sugestion comes in hand in any problem solution but I know that it can very easily come out of hand, I worked on a system where everything was passed down through 2 parameters, that where in fact 2 arrays of parameters.
The system was a mess, very hard to understand and to test, and bugs popped around in production time.
May the code be with you. -
Is it absolutely necessary to have a constructor method in a class? I realise it might not be good programming practice, but would be glad of any opinions.
Every class always has at least one constructor. If you don't provide one explicitly, the compiler inserts one that takes no arguments and does nothing but call the superclass' no-arg constructor.
http://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html
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. -
Difference between constructor & Methods if any ?
In the below code I use the constructor ConstructorShirt1('M') to pass the value of M to the class ConstructorShirt1, but why do we have to do this, instead can we not just use a method and write the same thing in a method.
class ConstructorShirt1Test {
public static void main (String args[]) {
ConstructorShirt1 constShirt = new ConstructorShirt1('M');
char colorCode;
colorCode = constShirt.getColorCode();
System.out.println("Color Code: " + colorCode);
class ConstructorShirt1 {
private int shirtID = 0; // Default ID for the shirt
private String description = "-description required-"; // default
// The color codes are R=Red, B=Blue, G=Green, U=Unset
private char colorCode = 'U';
private double price = 0.0; // Default price for all items
private int quantityInStock = 0; // Default quantity for all items
public ConstructorShirt1(char startingCode) {
switch (startingCode) {
case 'R':
case 'G':
case 'B':
colorCode = startingCode;
break;
default:
System.out.println("Invalid colorCode. Use R, G, or B");
public char getColorCode() {
return colorCode;
} // end of class
So I am not clear what is the difference between constructor and methods if any ? or if not when to use a constructor and when to use a method.
I would be glad if somebody throws light on this topic.
PKThere shouldn't be any confusion on this one... a constructor is meant to create an instance of the class. It can also set the state of its member variables in the process, like the constructor you are using. The same can also be done by a method.
Wouldn't make much of a difference for simple programs, but this is more pertinent when it comes to designing classes. Like if the developer using the class needs to know what all states he has to set before he needs to do anything useful, then it is better to provide a constructor with some arguments for doing that. -
Reg Servlet's inti method and Constructor method
Hi,
My friend asks me 'Is init method of servlet is necessary? Can't we do whatever we want to do in Init method, in the constructor of the servlet? Why is init method is necessary?'
Thanks in advance,
Guhanyou can get the config object from the init method which u cant get from constructors. The environment details of the servlet can be had from it...
-
Hello,
I want to write a class that heritances behaviour and porpoerties of the superclass. Is it possible to execute the methods of the superclass in the subclass? Instead I could write a method in the superclass and call it inside constructor of the subclass, but that seems like a trick to me.Is it possible to execute the methods of the superclass in the
subclass? Instead I could write a method in the superclass and call it
inside constructor of the subclass, but that seems like a trick to me.
If you are talking about calling super class constructor in subclass, you can do that:
public function SubClassConstructor(){
super();
If you need to call function of superclass, well, you have to write it in superclass, right? Just make it either public or protected. -
Can't get stage from a constructor method. Why?
Hi,
I'm making a kind of image showcase, what has a fluid width and height, depending on browser window dimensions. Everything is okay, I have other kind of issue: in constructor function in this gallery class I can't use stage property, I have to get it from main class.
Why Flash treats me this way and how I can avoid this currentStage variable?
Main code:
package dev {
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.display.MovieClip;
import flash.events.Event;
import UI.BackgroundImageRotator;
public class Application extends Sprite {
public function Application():void {
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
trace("Start.");
var BIR = new BackgroundImageRotator(stage);
stage.addChild(BIR);
BackgroundImageRotator class:
package UI {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
public class BackgroundImageRotator extends MovieClip {
protected var currentStage:Stage;
public function BackgroundImageRotator(currentStage:Stage):void {
this.x = 0;
this.y = 0;
this.currentStage = currentStage;
currentStage.addEventListener(Event.RESIZE, onStageResize);
protected function onStageResize(evt:Event):void {
trace(stage.stageWidth + ' ' + stage.stageHeight);if you have a display object that will be added to the display list, you need to wait until it is added before you can reference its stage property. ie, use the Event.ADDED_TO_STAGE event.
otherwise, you must pass a stage reference to your class. -
Error while calling a super class public method in the subclass constructor
Hi ,
I have code like this:
CLASS gacl_applog DEFINITION ABSTRACT.
PUBLIC SECTION.
METHODS:
create_new_a
IMPORTING pf_obj TYPE balobj_d
pf_subobj TYPE balsubobj
pf_extnumber TYPE string
EXPORTING pfx_log_hndl TYPE balloghndl
EXCEPTIONS error
ENDCLASS.
CLASS gacl_applog IMPLEMENTATION.
METHOD create_new_a.
DATA: ls_log TYPE bal_s_log.
Header aufsetzen
MOVE pf_extnumber TO ls_log-extnumber.
ls_log-object = pf_obj.
ls_log-subobject = pf_subobj.
ls_log-aluser = sy-uname.
ls_log-alprog = sy-repid.
ls_log-aldate = sy-datum.
ls_log-altime = sy-uzeit.
ls_log-aldate_del = ls_log-aldate + 1.
CALL FUNCTION 'BAL_LOG_CREATE'
EXPORTING
i_s_log = ls_log
IMPORTING
e_log_handle = pfx_log_hndl
EXCEPTIONS
OTHERS = 1.
IF ( sy-subrc NE 0 ).
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
RAISING error.
ENDIF.
ENDMETHOD.
CLASS gcl_applog_temp DEFINITION INHERITING FROM gacl_applog.
PUBLIC SECTION.
DATA: log_hndl TYPE balloghndl READ-ONLY
, t_log_hndl TYPE bal_t_logh READ-ONLY
METHODS: constructor
IMPORTING pf_obj TYPE balobj_d
pf_subobj TYPE balsubobj
pf_extnumber TYPE string
EXCEPTIONS error
, msg_add REDEFINITION
, display REDEFINITION
ENDCLASS.
CLASS gcl_applog_temp IMPLEMENTATION.
METHOD constructor.
CALL METHOD create_new_a
EXPORTING pf_obj = pf_obj
pf_subobj = pf_subobj
pf_extnumber = pf_extnumber
IMPORTING pfx_log_hndl = log_hndl.
IF ( sy-subrc NE 0 ).
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
RAISING error.
ENDIF.
ENDMETHOD.
A public method of Super class has been called from the constructor of the sub class. we are getting the syntax error :
' In the constructor method, you can only access instance attributes, instance methods, or "ME" after calling the constructor of the superclass '
Can you please suggest how to change the code with out affecting the functioanlity.
Thank you ,
Lakshmi.Hi,
Call that method by instance of Subclass. OR
SUPER-->method.
Read very useful document
Constructors
Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class.
The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows:
METHODS CONSTRUCTOR
IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
EXCEPTIONS.. <ei>.
and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement.
The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows:
CLASS-METHODS CLASS_CONSTRUCTOR.
and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class.
Pls. reward if useful.... -
Abstract classes and constructors - cannot call abs. methods in CONSTRUCTOR
Let me explain the scenario:
I'm building a program in which I need to read a file (among other things) and I intend to use object orientation to it's fullest in doing so. I thought of creating an abstract FILE class which has the commonalities, and two subclasses SERVER_FILE and PC_FILE, which implement the abstract method GET_CONTENTS in different ways (OPEN DATASET / GUI_UPLOAD), same for the CHOOSE method which allows to select the file from it's corresponding source.
Initially I've used an interface but since another tasks like setting the file path are common for both, switched to an ABSTRACT class.
Now, the problem is, from the main code I intend to use a FILE reference to handle either type of file. At the instantiation moment I'd like the path attribute to be set; if it was not set by parameter, i'd like to call the CHOOSE method which is abstract for the superclass. Since this is common for either subclass, I need a way to code it once in the superclass. But I get an error because the CHOOSE method is abstract.
This is the problem code (extracts):
* CLASS lcl_file DEFINITION
CLASS lcl_file DEFINITION ABSTRACT.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING
i_path TYPE string OPTIONAL
EXCEPTIONS
no_path_chosen,
get_contents ABSTRACT
RETURNING
value(rt_contents) TYPE string_table
EXCEPTIONS
read_error.
PROTECTED SECTION.
DATA:
_v_path TYPE string.
METHODS:
choose ABSTRACT
EXCEPTIONS
no_path_chosen,
set_path
IMPORTING
i_path TYPE string.
ENDCLASS. "lcl_file DEFINITION
* CLASS lcl_file IMPLEMENTATION
CLASS lcl_file IMPLEMENTATION.
METHOD constructor.
IF i_path IS SUPPLIED.
CALL METHOD set_path
EXPORTING
i_path = i_path.
ELSE.
*---->>>> PROBLEM CALL - CAN'T BE DONE!!
CALL METHOD choose
EXCEPTIONS
no_path_chosen = 1.
IF sy-subrc = 1.
RAISE no_path_chosen.
ENDIF.
ENDIF.
ENDMETHOD. "constructor
METHOD set_path.
_v_path = i_path.
ENDMETHOD. "set_path
ENDCLASS. "lcl_file IMPLEMENTATION
* CLASS lcl_server_file DEFINITION
CLASS lcl_server_file DEFINITION
INHERITING FROM lcl_file.
PUBLIC SECTION.
METHODS:
get_contents REDEFINITION.
PROTECTED SECTION.
METHODS:
choose REDEFINITION.
ENDCLASS. "lcl_server_file DEFINITIO
* CLASS lcl_server_file IMPLEMENTATION
CLASS lcl_server_file IMPLEMENTATION.
METHOD choose.
DATA:
l_i_path TYPE dxfields-longpath,
l_o_path TYPE dxfields-longpath.
CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
EXPORTING
i_location_flag = 'A' " Application server
i_path = l_i_path
fileoperation = 'R' " Lectura
IMPORTING
o_path = l_o_path
EXCEPTIONS
rfc_error = 1
OTHERS = 2.
IF sy-subrc = 0 AND l_o_path <> l_i_path.
MOVE l_o_path TO _v_path.
ELSE.
RAISE no_path_chosen.
ENDIF.
ENDMETHOD. "choose
METHOD get_contents.
DATA: l_line LIKE LINE OF rt_contents,
l_osmsg TYPE string.
CHECK NOT _v_path IS INITIAL.
OPEN DATASET _v_path FOR INPUT
IN TEXT MODE
MESSAGE l_osmsg.
IF sy-subrc <> 0.
MESSAGE e000(oo) WITH l_osmsg
RAISING read_error.
ELSE.
DO.
READ DATASET _v_path INTO l_line.
IF sy-subrc = 0.
APPEND l_line TO rt_contents.
ELSE.
EXIT.
ENDIF.
ENDDO.
CLOSE DATASET _v_path.
ENDIF.
ENDMETHOD. "get_contents
ENDCLASS. "lcl_server_file IMPLEMENTATION
* CLASS lcl_pc_file DEFINITION
CLASS lcl_pc_file DEFINITION
INHERITING FROM lcl_file.
PUBLIC SECTION.
METHODS:
get_contents REDEFINITION.
PROTECTED SECTION.
METHODS:
choose REDEFINITION.
ENDCLASS. "lcl_pc_file DEFINITIO
* CLASS lcl_pc_file IMPLEMENTATION
CLASS lcl_pc_file IMPLEMENTATION.
METHOD choose.
DATA:
l_i_path TYPE dxfields-longpath VALUE 'C:\',
l_o_path TYPE dxfields-longpath.
CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
EXPORTING
i_location_flag = 'P' " PC
i_path = l_i_path
fileoperation = 'R' " Lectura
IMPORTING
o_path = l_o_path
EXCEPTIONS
rfc_error = 1
OTHERS = 2.
IF sy-subrc = 0 AND l_o_path <> l_i_path.
MOVE l_o_path TO _v_path.
ELSE.
RAISE no_path_chosen.
ENDIF.
ENDMETHOD. "choose
METHOD get_contents.
CHECK NOT _v_path IS INITIAL.
CALL METHOD cl_gui_frontend_services=>gui_upload
EXPORTING
filename = _v_path
CHANGING
data_tab = rt_contents
EXCEPTIONS
file_open_error = 1
file_read_error = 2
no_batch = 3
gui_refuse_filetransfer = 4
invalid_type = 5
no_authority = 6
unknown_error = 7
bad_data_format = 8
header_not_allowed = 9
separator_not_allowed = 10
header_too_long = 11
unknown_dp_error = 12
access_denied = 13
dp_out_of_memory = 14
disk_full = 15
dp_timeout = 16
OTHERS = 17.
IF sy-subrc <> 0.
RAISE read_error.
ENDIF.
ENDMETHOD. "get_contents
ENDCLASS. "lcl_pc_file IMPLEMENTATION
* Data
DATA: gr_file TYPE REF TO lcl_file.
* Main Program
START-OF-SELECTION.
* Get text lines from file
IF p_srv = abap_true.
CREATE OBJECT gr_file
TYPE
lcl_server_file
EXCEPTIONS
no_path_chosen = 1.
ELSE.
CREATE OBJECT gr_file
TYPE
lcl_pc_file
EXCEPTIONS
no_path_chosen = 1.
ENDIF.
On a 4.6c system this code gave me a dump, while on my NW7.0 SP it doesn't even activate with the following error:
You cannot call abstract methods in the "CONSTRUCTOR" method.
- Following some suggestions from Java forums i've tried to define the constructor in the base class as PROTECTED or PRIVATE instead, then calling super->constructor from the subclasses, but I get this error in german:
Sichtbarkeit des Konstruktors darf nicht spezieller als die Sichtbarkeit der Instanzerzeugung (CREATE-Zuzatz) sein.
which Altavista translates like:
Visibility of the constructor may not be more special than the
visibility of the instance production (CREATE Zuzatz).
- I've also thought of defining the CHOOSE method as a class (not instance) one, then calling it before creating the file object which maybe solves the problem, but I see that approach more "procedural oriented" which i'm trying to avoid.
- Of course I could define a constructor for each subclass, but both would have exactly the same code.
I'm really lost on how should I code this. My main focus is on avoiding code dupplication.
I hope someone with more OO experience can see what I'm trying to do and sheds some light.
Many thanks for reading all this!Dear Alejandro,
When i saw your code, you are trying to access an astract method CHOOSE(which is actually implemented in sub class) from the constructor of the base class which is not possible. By this time, we don't know which sub class it is refering to, so it gives an error. I see two solutions for this..
1. To define constructor in sub class and call the choose method from the consturctor of the sub class(which in this case is reputation of the same again for each sub class)
2. Remove the calling of choose method from the constructor of the main class and call it separately(after creating the object). By now we know which sub class we are refering to. I would have designed the program in the following way.
* CLASS lcl_file DEFINITION
CLASS lcl_file DEFINITION ABSTRACT.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING
i_path TYPE string OPTIONAL
EXCEPTIONS
no_path_chosen,
get_contents ABSTRACT
RETURNING
value(rt_contents) TYPE string_table
EXCEPTIONS
read_errorm,
set_path ABSTRACT
EXCEPTIONS
no_path_chosen.
PROTECTED SECTION.
DATA:
_v_path TYPE string.
* METHODS:
* choose ABSTRACT
* EXCEPTIONS
* no_path_chosen,
* set_path ABSTRACT
* IMPORTING
* i_path TYPE string.
ENDCLASS. "lcl_file DEFINITION
* CLASS lcl_file IMPLEMENTATION
CLASS lcl_file IMPLEMENTATION.
METHOD constructor.
IF i_path IS SUPPLIED.
_v_path = i_path.
* CALL METHOD set_path
* EXPORTING
* i_path = i_path.
* ELSE.
**---->>>> PROBLEM CALL - CAN'T BE DONE!!
* CALL METHOD choose
* EXCEPTIONS
* no_path_chosen = 1.
* IF sy-subrc = 1.
* RAISE no_path_chosen.
* ENDIF.
ENDIF.
ENDMETHOD. "constructor
* METHOD set_path.
* _v_path = i_path.
* ENDMETHOD. "set_path
ENDCLASS. "lcl_file IMPLEMENTATION
* CLASS lcl_server_file DEFINITION
CLASS lcl_server_file DEFINITION
INHERITING FROM lcl_file.
PUBLIC SECTION.
METHODS:
get_contents REDEFINITION,
set_path REDEFINITION.
* PROTECTED SECTION.
* METHODS:
* choose REDEFINITION.
ENDCLASS. "lcl_server_file DEFINITIO
* CLASS lcl_server_file IMPLEMENTATION
CLASS lcl_server_file IMPLEMENTATION.
METHOD set_path.
DATA:
l_i_path TYPE dxfields-longpath,
l_o_path TYPE dxfields-longpath.
CHECK _v_path IS INITIAL.
CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
EXPORTING
i_location_flag = 'A' " Application server
i_path = l_i_path
fileoperation = 'R' " Lectura
IMPORTING
o_path = l_o_path
EXCEPTIONS
rfc_error = 1
OTHERS = 2.
IF sy-subrc = 0 AND l_o_path = l_i_path.
MOVE l_o_path TO _v_path.
ELSE.
RAISE no_path_chosen.
ENDIF.
ENDMETHOD. "set_path
METHOD get_contents.
DATA: l_line LIKE LINE OF rt_contents,
l_osmsg TYPE string.
CHECK NOT _v_path IS INITIAL.
* OPEN DATASET _v_path FOR INPUT
* IN TEXT MODE
* MESSAGE l_osmsg.
IF sy-subrc = 0.
* MESSAGE e000(oo) WITH l_osmsg
* RAISING read_error.
ELSE.
DO.
READ DATASET _v_path INTO l_line.
IF sy-subrc = 0.
APPEND l_line TO rt_contents.
ELSE.
EXIT.
ENDIF.
ENDDO.
CLOSE DATASET _v_path.
ENDIF.
ENDMETHOD. "get_contents
ENDCLASS. "lcl_server_file IMPLEMENTATION
* CLASS lcl_pc_file DEFINITION
CLASS lcl_pc_file DEFINITION
INHERITING FROM lcl_file.
PUBLIC SECTION.
METHODS:
get_contents REDEFINITION,
set_path REDEFINITION.
* PROTECTED SECTION.
* METHODS:
* choose REDEFINITION.
ENDCLASS. "lcl_pc_file DEFINITIO
* CLASS lcl_pc_file IMPLEMENTATION
CLASS lcl_pc_file IMPLEMENTATION.
METHOD set_path.
DATA:
l_i_path TYPE dxfields-longpath VALUE 'C:\',
l_o_path TYPE dxfields-longpath.
CHECK _v_path IS INITIAL.
CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
EXPORTING
i_location_flag = 'P' " PC
i_path = l_i_path
fileoperation = 'R' " Lectura
IMPORTING
o_path = l_o_path
EXCEPTIONS
rfc_error = 1
OTHERS = 2.
IF sy-subrc = 0 AND l_o_path = l_i_path.
MOVE l_o_path TO _v_path.
ELSE.
RAISE no_path_chosen.
ENDIF.
ENDMETHOD. "set_path
METHOD get_contents.
CHECK NOT _v_path IS INITIAL.
CALL METHOD cl_gui_frontend_services=>gui_upload
EXPORTING
filename = _v_path
CHANGING
data_tab = rt_contents
EXCEPTIONS
file_open_error = 1
file_read_error = 2
no_batch = 3
gui_refuse_filetransfer = 4
invalid_type = 5
no_authority = 6
unknown_error = 7
bad_data_format = 8
header_not_allowed = 9
separator_not_allowed = 10
header_too_long = 11
unknown_dp_error = 12
access_denied = 13
dp_out_of_memory = 14
disk_full = 15
dp_timeout = 16
OTHERS = 17.
IF sy-subrc = 0.
* RAISE read_error.
ENDIF.
ENDMETHOD. "get_contents
ENDCLASS. "lcl_pc_file IMPLEMENTATION
* Data
DATA: gr_file TYPE REF TO lcl_file.
* Main Program
START-OF-SELECTION.
* Get text lines from file
IF abap_true = abap_true.
CREATE OBJECT gr_file
TYPE
lcl_server_file
EXCEPTIONS
no_path_chosen = 1.
ELSE.
CREATE OBJECT gr_file
TYPE
lcl_pc_file
EXCEPTIONS
no_path_chosen = 1.
ENDIF.
gr_file->set_path( ).
Regards
Kesava
Edited by: Kesava Chandra Rao on Mar 19, 2008 11:44 AM -
Object within Constructor with a method?
Hi,
Just trying to understand java code example and its various parts. i.e fields, constructor, methods etc. It is a Blackberry application.
I am mainly wondering about the part with the " HorizontalFieldManager(USE_ALL_WIDTH )". This has a method attached to it. So if this is the case it is an 'Object' within the UserInterface 'Constructor' that has a 'Method'?
And the semicolon at the end is not normally present on Methods is it?
Thanks.
//// EXAMPLE CODE ///
public class UserInterface extends UiApplication {
public static void main(String[] args) {
UserInterface theApp = new UserInterface();
theApp.enterEventDispatcher();
//constructor for UserInterface?
public UserInterface() {
pushScreen(new UserInterfaceScreen());
//UserInterfaceScreen class
final class UserInterfaceScreen extends MainScreen {
//fields or variables
HorizontalFieldManager _fieldManagerTop;
String _exchange, _convertedStr, _euroStr;
double _euros, _pounds, _converted;
int displayed = 0;
//constructor?
public UserInterfaceScreen() {
super();
LabelField title = new LabelField("Euro Calc",LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
setTitle(title);
_fieldManagerTop = new HorizontalFieldManager();
// An object with a method?
_fieldManagerGround = new HorizontalFieldManager(USE_ALL_WIDTH ) {
protected void paintBackground(Graphics graphics)
graphics.setBackgroundColor(0x00382B79);
graphics.clear();
super.paint(graphics);
};Edited by: duxbuz on Jul 9, 2009 3:20 AMHi,
this is a way to override the HorizontalFieldManager.paintBackground method whithout declaring a subclass inheriting from HorizontalFieldManager. See ANONYMOUS CLASSES in the following Link.
Jack -
Constructor Vs. Method Qustion
Hi,
i learn now about constructor in Abap and my question is ,
what is the advantage and disadvantage of using constructor oo,that i can build method that do the same action
e.g.
Regular Method:
METHODS: set_attributes IMPORTING
im_name TYPE string
im_planetype TYPE saplane-planetype,
display_attributes.
Constructor :
METHODS: constructor IMPORTING
im_name TYPE string
im_planetype TYPE saplane-planetype,
display_attributes.
in the constructor i use:
CREATE OBJECT r_plane
EXPORTING
im_name = 'LH_Barlin'
im_planetype = 'a321'.
and in Method :
CREATE OBJECT r_plane.
r_plane->set_attributes( im_name = 'LH_usa' im_planetype = 'bbb' ).
and both commend do the same :
RegardsFirst, you should post these questions in the ABAP Objects forum.
Anyway, you use the constructor to force certain actions when the instance is created. If you as designer of the class require that two attributes be set, then making them obligatory parameters ensures that an object can't be instantiated without those parameters being given some values. You could include some validation in the constructor as well to make sure that the values are valid.
If you don't put them in a constructor, you are relying on future developers - possibly even yourself - remembering to set those parameters after they've created.
One other advantage - it's one line of ABAP instead of three!
As ever though, which is better comes down to what specifically you're trying to do. It is usually better programming practice to leave as little to luck and remembering, as possible.
matt -
Help needed with if statement in a method
Hi I�ve created 2 string arrays. One holds a one digit user id no. and the other holds a 4 digit pin number. I�ve then written a method which should take the userId no that has been sent to the method in the UserCode parameter find the same number in the custid array if it does it should then check the same position of the pin array and check that the pin number matches the pin no. the method has received in PINCode parameter.
At the moment my method receives the parameters checks the userId no. but doesn�t move on and check the PIN array.
Any help would be great as I�ve been staring at this for days now and I can�t see the wood from the trees!
public boolean checkPinAndUserId(String pinCode, String userCode)
boolean found = false;
for (int i = 0; i < userId.length; i++)
if (userCode.equals(userId))
if (pinCode.equals(pin[i]))
found = true;
return found;I've posted my code in full so hopefully everyone can see exactly what I have been doing.
Note - my code uses the observer/observable model. The method I am having the problem with the if statement is in the class HSBC as are the string arrays. in the class ATM in the action performed PINInput button events section, when the pin count reaches 4 it sends the parameters over to the HSBC checkpin&userid method.
I've used the System.out.println() statements to see what's going on and it receives the parameters checkes the userid array but does not move on to check that the pin parameter matches the pin array?
Any help would be great - Hope this helps.
* @(#)BankAssignment.java 1.0 03/04/06
* This apllication l
package myprojects.bankassignment;
import java.awt.*; // import the component library
import java.awt.event.*; // import the evnet library
import javax.swing.*;
import java.util.*;
class Correct1v16 extends Frame // make a new application
public Correct1v16() // this is the constructor method
HSBC HSBCobj = new HSBC();
public static void main(String args[]) // this invokes the constructor of the class and creates a runable object 'mainframe'
Correct1v16 mainFrame = new Correct1v16(); // the constructor call of the class which creates an object of that class
class HSBC implements Observer, ActionListener
Frame f5;
JLabel refill, launch;
TextField tRefill, tLaunch;
JButton refillbut, launchbut;
int count;
String [] userId=new String [10];
String [] pin=new String [10];
public boolean authenticate = false;
int i;
public HSBC()
drawFrame();
Atm Atmobj = new Atm(this);
System.out.println("Starting HSBC constructor");
public void drawFrame()
System.out.println("Start HSBC drawframe method...");
f5=new Frame("HSBC");
f5.setLayout(new FlowLayout());
f5.setSize(200, 200);
f5.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
f5.dispose();
System.exit(0);
refill=new JLabel("Refill ATM");
launch=new JLabel("Launch new ATM");
tRefill=new TextField(20);
tLaunch=new TextField(10);
refillbut=new JButton("Refill ATM");
refillbut.addActionListener(this);
launchbut=new JButton("Launch new ATM");
launchbut.addActionListener(this);
f5.add(refill);
f5.add(tRefill);
f5.add(refillbut);
f5.add(launch);
f5.add(tLaunch);
f5.add(launchbut);
f5.setVisible(true);
//*********** POPULATE THE ARRAYS */
pin[0]="1234";
pin[1]="2345";
pin[2]="3456";
pin[3]="4567";
pin[4]="5678";
pin[5]="6789";
pin[6]="7890";
pin[7]="8901";
pin[8]="9012";
pin[9]="0123";
userId[0]="0";
userId[1]="1";
userId[2]="2";
userId[3]="3";
userId[4]="4";
userId[5]="5";
userId[6]="6";
userId[7]="7";
userId[8]="8";
userId[9]="9";
}// end drawframe method
// public Atm atmLink = (Atm)o;
public void update(Observable gm1, Object o)
Atm atmLink = (Atm)o;
tRefill.setText("Refill ATM ?");
atmLink.refill();
}//end update method
public void actionPerformed(ActionEvent ae)
if(ae.getSource() == refillbut)
// Atm Atmobj.refill();
// tRefill.setText("text area");
// atmLink.refill();
// Atmobj.refill();
// setChanged();
// notifyObservers();
if(ae.getSource() == launchbut)
tLaunch.setText("new ATM opened");
Atm Atmobj1 = new Atm(this);
//******** THIS METHOD RECEIVES THE PARAMETERS FROM THE ATM METHOD (LINE 580) (PINCODE AND USERCODE) BUT
//******** IT ONLY THE ARRAY CALLED USERID (WHICH HOLDS THE USER CODE MATCHES ONE OF THE USERID'S)
//******** I DO WANT IT TO DO THIS BUT I ALSO WANT IT TO MOVE ON AND CHECK THE PINCODE WITH THE PIN ARRAY)
//******** IF THEY ARE BOTH TRUE I WANT IT TO RETURN TRUE - ELSE FALSE. */
public boolean checkPinAndUserId(String pinCode, String userCode)
boolean found = false;
System.out.println("in checkpin method");
for (int i = 0; i < userId.length; i++)
System.out.println("in the userid array" + userId);
if (userCode.equals(userId[i]))
System.out.println("checking user code array");
if (pinCode.equals(pin[i]))
System.out.println("checking the pin array" + pinCode);
System.out.println("pin[i] = "+pin[i]);
found = true;
return found;
}// end HSBC class
class Atm extends Observable implements ActionListener
Frame f1;
TextField t3, t5;
JTextArea display = new JTextArea("Welcome to HSBC Bank. \n Please enter your User Identification number \n", 5, 40);
JPanel p1, p2, p3,p4;
private JButton but1, but2, but3, but4,but5,but6,but7,but8,but9,but0,enter,
cancel,fivepounds,tenpounds,twentypounds,fiftypounds,clearbut, refillbut;
int state = 1;
public String pinCode ="";
public String userCode ="";
int userCodeCount = 0;
int PINCount = 0;
String withdrawAmount = "";
int atmBalance =200;
private HSBC HSBCobj;
//ATM constructor that receives the HSBCobj g1 reference to where the HSBC class
// in in the program
// Calls the drawATMFrame method
// add the observer to the HSBCobj reference so that the ATM can tell HSBC that
// something has changed
public Atm(HSBC g1)
HSBCobj = g1;
drawATMFrame();
System.out.println("Starting Atm constructor");
addObserver(HSBCobj);
// this is the method that draws the ATM interface
// also apply the Border Layout to the frame
public void drawATMFrame()
f1=new Frame("ATM");
f1.setLayout(new BorderLayout());
f1.setSize(350, 250);
f1.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
f1.dispose();
System.exit(0);
// declare & instantiate all the buttons that will be used on the ATM
but1 =new JButton("1");
but1.addActionListener(this);
but2 =new JButton("2");
but2.addActionListener(this);
but3 =new JButton("3");
but3.addActionListener(this);
but4 =new JButton("4");
but4.addActionListener(this);
but5 =new JButton("5");
but5.addActionListener(this);
but6 =new JButton("6");
but6.addActionListener(this);
but7 =new JButton("7");
but7.addActionListener(this);
but8 =new JButton("8");
but8.addActionListener(this);
but9 =new JButton("9");
but9.addActionListener(this);
but0 =new JButton("0");
but0.addActionListener(this);
enter=new JButton("Enter");
enter.addActionListener(this);
cancel=new JButton("Cancel/ \n Restart");
cancel.addActionListener(this);
fivepounds =new JButton("?5");
fivepounds.addActionListener(this);
tenpounds = new JButton("?10");
tenpounds.addActionListener(this);
twentypounds = new JButton("?20");
twentypounds.addActionListener(this);
fiftypounds = new JButton("?50");
fiftypounds.addActionListener(this);
clearbut = new JButton("Clear");
clearbut.addActionListener(this);
refillbut = new JButton("Refill");
refillbut.addActionListener(this);
//declare & instantiate a textfield
t3=new TextField(5);
// instantiate 4 JPanels
p1=new JPanel();
p2=new JPanel();
p3=new JPanel();
p4=new JPanel();
// add some buttons to p1
p1.add(but1);
p1.add(but2);
p1.add(but3);
p1.add(but4);
p1.add(but5);
p1.add(but6);
p1.add(but7);
p1.add(but8);
p1.add(but9);
p1.add(but0);
//add the text area field to p2
p2.add(display);
// apply the grid layout to p3
GridLayout layout3 = new GridLayout(4,1,5,5);
p3.setLayout(layout3);
p3.add(fivepounds);
p3.add(tenpounds);
p3.add(twentypounds);
p3.add(fiftypounds);
// apply grid layout to p4
GridLayout layout4 = new GridLayout(4,1,5, 5);
p4.setLayout(layout4);
p4.add(clearbut);
p4.add(enter);
p4.add(cancel);
p4.add(refillbut);
//add the panels to the different parts of the screen
f1.add("North", display);
f1.add("Center", p1);
f1.add("East", p4);
f1.add("West", p3);
f1.setVisible(true);
}// end drawATMframe method
public void actionPerformed(ActionEvent ae)
if(state == 1)
getUserIdNo(ae);
else if(state == 2)
doPINInput(ae);
else
withdrawCash(ae);
}// end action performed method
//******** STATE 1 events
//******** USER ID INPUT
public void getUserIdNo (ActionEvent ae)
if (ae.getSource() == but1)
display.append("*");
userCode = userCode + "1";
userCodeCount++;
if (ae.getSource() == but2)
display.append("*");
userCode = userCode + "2";
userCodeCount++;
if (ae.getSource() == but3)
display.append("*");
userCode = userCode + "3";
userCodeCount++;
System.out.println("user id ="+userCode);
if (ae.getSource() == but4)
display.append("*");
userCode = userCode = "4";
userCodeCount++;
System.out.println("user id ="+userCode);
if (ae.getSource() == but5)
display.append("*");
userCode = userCode + "5";
userCodeCount++;
System.out.println("user id ="+userCode);
if (ae.getSource() == but6)
display.append("*");
userCode = userCode + "6";
userCodeCount++;
System.out.println("user id ="+userCode);
if (ae.getSource() == but7)
display.append("*");
userCode = userCode + "7";
userCodeCount++;
System.out.println("user id ="+userCode);
if (ae.getSource() == but8)
display.append("*");
userCode = userCode + "8";
userCodeCount++;
System.out.println("user id ="+userCode);
if (ae.getSource() == but9)
display.append("*");
userCode = userCode + "9";
userCodeCount++;
System.out.println("user id ="+userCode);
if (ae.getSource() == but0)
display.append("*");
userCode = userCode + "0";
userCodeCount++;
System.out.println("user id ="+userCode);
if (ae.getSource() == cancel)
display.setText("Welcome to HSBC Bank.\n Please enter your User Identification number \n");
userCode = "";
state = 2;
if (ae.getSource() == clearbut)
display.setText("Please enter your user ID number again\n");
userCode = "";
userCodeCount = 0;
if (ae.getSource() == refillbut)
refill();
if (ae.getSource() == enter)
display.setText("Please enter your PIN \n");
state = 2;
System.out.println(" User id enter button = " + userCode);
if (userCodeCount == 1)
display.setText("Please enter your PIN \n");
userCode = "";
userCodeCount = 0;
state = 2;
//******** STATE 2
//******** PIN INPUT
public void doPINInput(ActionEvent ae)
if (ae.getSource() == but1)
{ pinCode = pinCode.concat("1");
display.append("*");
PINCount++;
if (ae.getSource() == but2)
{ pinCode = pinCode.concat("2");
display.append("*");
PINCount++;
if (ae.getSource() == but3)
{ pinCode = pinCode.concat("3");
display.append("*");
PINCount++;
if (ae.getSource() == but4)
{ pinCode = pinCode.concat("4");
display.append("*");
PINCount++;
if (ae.getSource() == but5)
{ pinCode = pinCode.concat("5");
display.append("*");
PINCount++;
if (ae.getSource() == but6)
{ pinCode = pinCode.concat("6");
display.append("*");
PINCount++;
if (ae.getSource() == but7)
{ pinCode = pinCode.concat("7");
display.append("*");
PINCount++;
if (ae.getSource() == but8)
{ pinCode = pinCode.concat("8");
display.append("*");
PINCount++;
if (ae.getSource() == but9)
{ pinCode = pinCode.concat("9");
display.append("*");
PINCount++;
if (ae.getSource() == but0)
{ pinCode = pinCode.concat("0");
display.append("*");
PINCount++;
if (ae.getSource() == clearbut)
display.setText("Please enter your PIN number again \n");
pinCode = "";
PINCount = 0;
if (ae.getSource() == cancel)
display.setText("Welcome to HSBC Bank.\n Please enter your User Identification number \n");
state = 1;
pinCode ="";
PINCount = 0;
if (ae.getSource() == refillbut)
refill();
/// ************************ THIS BUTTON SENDS THE PIN & USER CODE OVER TO THE MAIN BANK
/// ************************ (LINE 152)
if (ae.getSource() == enter)
// if(HSBCobj.checkPinAndUserId(pinCode, userCode))
// display.setText("How much would you like to withdraw \n");
// else
// display.setText("Your UserId and Pin code do not match");
if(PINCount ==4)
if(HSBCobj.checkPinAndUserId(userCode,pinCode))
display.setText("Enter the amount you \n want to withdraw \n ?");
PINCount=0;
else
display.setText("Your User Identification Number \n and PIN number do not match! \n please try again\n");
//*********** STATE 3 events
//*********** withdrawCash
public void withdrawCash(ActionEvent ae)
// if (ae.getSource() == but1)
// display.append("1");
/// withdrawAmount = withdrawAmount+1;
// pinCode = pinCode.concat("2");
// System.out.println("Withdrawal Amount = "+withdrawAmount);
if(ae.getSource( ) == but1)
withdrawAmount = withdrawAmount + "1";
display.setText(withdrawAmount);
if(ae.getSource( ) == but2)
withdrawAmount = withdrawAmount + "2";
display.setText(withdrawAmount);
if(ae.getSource( ) == but3)
withdrawAmount = withdrawAmount + "3";
display.setText(withdrawAmount);
if(ae.getSource( ) == but4)
withdrawAmount = withdrawAmount + "4";
display.setText(withdrawAmount);
if(ae.getSource( ) == but5)
withdrawAmount = withdrawAmount + "5";
display.setText(withdrawAmount);
if(ae.getSource( ) == but6)
withdrawAmount = withdrawAmount + "6";
display.setText(withdrawAmount);
if(ae.getSource( ) == but7)
withdrawAmount = withdrawAmount + "7";
display.setText(withdrawAmount);
if(ae.getSource( ) == but8)
withdrawAmount = withdrawAmount + "8";
display.setText(withdrawAmount);
if(ae.getSource( ) == but9)
withdrawAmount = withdrawAmount + "9";
display.setText(withdrawAmount);
if(ae.getSource( ) == but0)
withdrawAmount = withdrawAmount + "0";
display.setText(withdrawAmount);
if (ae.getSource() == fivepounds)
withdrawAmount = withdrawAmount + "5";
display.setText(withdrawAmount);
atmBalance();
if (ae.getSource() == tenpounds)
withdrawAmount = withdrawAmount + "10";
display.setText(withdrawAmount);
atmBalance();
if (ae.getSource() == twentypounds)
withdrawAmount = withdrawAmount + "20";
display.setText(withdrawAmount);
atmBalance();
if (ae.getSource() == fiftypounds)
withdrawAmount = withdrawAmount + "50";
display.setText(withdrawAmount);
atmBalance();
// if (ae.getSource() == tenpounds)
// display.append("10");
// withdrawAmount = 10;
// pinCode = pinCode.concat("2");
// System.out.println("10 pound button pressed");
// atmBalance();
if (ae.getSource() == enter)
atmBalance();
if (ae.getSource() == refillbut)
System.out.println("refill but pressed");
refill();
if (ae.getSource() == clearbut)
System.out.println("clear but pressed");
display.setText("Enter the amount you want to withdraw \n ?");
withdrawAmount="";
if (ae.getSource() == cancel)
display.setText("Welcome to HSBC Bank.\n Please enter your User Identification number \n");
withdrawAmount="";
pinCode ="";
PINCount = 0;
userCode = "";
userCodeCount = 0;
state = 1;
}// end withdraw cash input method
// checks balace of atm and withdraws cash. Also notifies onserver if atm balance is low
public void atmBalance()
String s = withdrawAmount;
int n = Integer.parseInt(s);
if ( atmBalance >= n)
atmBalance = atmBalance - n;
System.out.println("atm balance = "+ atmBalance);
display.setText("Thankyou for using HSBC. \nYou have withdrawn ?"+n);
if (atmBalance<40)
System.out.println("atm balance is less than 40 - notify HSBC" );
setChanged();
notifyObservers(this);
/// note the refil should send a message to the controller
// advising a refil is needed. The Bank will send an engineer
// out who will fill the atm up
}// end atmBalance method
/// note the refil should send a message to the controller
/// then th coontroller will send a message to this method to fill machine
/// (this is simulating a clerk filling atm)
public void refill()
System.out.println("in refill method" );
atmBalance = 200;
System.out.println("Atm has been refilled. Atm balance = " + atmBalance);
// setChanged();
// notifyObservers(this);
}// end refill method
// NOTE SURE ABOUT THIS - DO I USE THE UPDATE METHOD TO NOTIFY HSBC THAT ATM REQUIRES FILLING
// THIS IS THE WRONG PART OF THE PROGRAM (SHOULD BE IN HSBC) - IGNORE
public void update(Observable gm1, Object gameObj)
display.setText("Congratulations");
}//end update method
}// end Atm method
}// end Assignment2 class
Maybe you are looking for
-
I can't add movies to my iTunes library !!
I transfered the movie from one computer to the other with a USB. When I draged the file to iTunes library it was accepted in computer 2 (Which is a laptop) However when I tried this on my Pc nothing happened. By testing on the laptop i'm sure the fo
-
Pop-up message when Launching Firefox Mozilla
Just updated Mozilla Firefox to 3.6.10 recently, and now every time when I launch Firefox. I will receive this message: "what happened:TypeError: this.installDir is null. " on a small window. click ok than the program will launched. Noted that this h
-
E-Recruiting 603 HCM_ERC_SES_1
Hi Sap brains, We are implementing ERECRUIT603 with the following business function sets, HCM_ERC_SES_1, HCM_TM_ANALYTICS_1, HCM_ERC_CI_1. We have problem with HCM_ERC_SES_1, as we have activated it, we are configuring search functions with SES (Sear
-
I've run into a little problem. I'm using my own custom Cell factory and renderer for a TreeView. In this renderer I bind() certain properties of the TreeItem's value to Label and other controls that together form my cell. The reason I like to bind t
-
Why can't I find Podcast Producer under Share in the latest version of FCPX?
We had our Wiki/blog server set up to publish videos directly to Podcast Producer from FCPX? This summer we upgraded the server to Lion and updated FCPX and the "Podcast Producer" option is gone from the "Share" menu. Why would they do this? What i