Classes, and constructors and instance variables . . . oh my!

wow, I am really struggling with the stuff we are doing in class for the last few days. I am going to post our assignment and point out specific things I don't understand. I don't understand some of the syntax and the overall logical flow of how parameters get passed back and forth, etc. I have been over our book and class examples and I am still confused.
Here is one part of the assignment:
"Create two instances of the MyDate class named begDate and endDate, by using the MyDate constructor after having prompted the user
3 times for each date for values of a valid month, day, and year."
Q: how do I create two instances using the constructor?
(from our assignment) "Within the MyDate class:
     Include three private int variables, named month, day, and year.
     Include a constructor that sets (sets them to what?!) the values of month, day, and year."
here is what I have:
public class MyDate {
     private int month, day, year;
     public MyDate (int month, int day, int year){
          month = 0;
          day = 0;
          year = 0;
     }//MyDate Constructor(from our assignment) "Create two instances of the MyDate class named begDate and endDate, by using the MyDate constructor after having prompted the user 3 times for each date for values of a valid month, day, and year."
and here is what I have in the executable class (it isn't much because I already have an error; it says I can't convert String to MyDate):
public static void main(String[] args) {
          MyDate begDate = JOptionPane.showInputDialog("beg. month?");
     }I guess I don't know how to use the constructor correctly. Sorry, but I have tried to make this as clear as possible.

I will give you a start:
public static void main(String[] args) {
          MyDate begDate new MyDate(JOptionPane.showInputDialog("beg. month?"), JOptionPane.showInputDialog("beg. day?"), JOptionPane.showInputDialog("beg. year?"));
public class MyDate {
     private int month, day, year;
     public MyDate (int month, int day, int year){
          this.month = month;
          this.day = day;
          this.year = year;
     }//MyDate Constructor
/code]
Haven't tested it, maybe made some type mismatches, but at leasy try this one                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Static Class Function vs. Instance Variables

    I'm making a Wheel class to spin the wheels on some toy
    trains as they move back and forth.
    Each wheel on the train is an instance of the Wheel class and
    there are several of them.
    I thought it would be great to just have a static class
    function to tell all the Wheels to start turning:
    Wheel.go();
    The Wheel class keeps a static array of all of its instances
    so I thought I would just loop through all of those instances and
    issue the wheelInstance.roll() method.
    So far it all works. But I was planning to use a setInterval
    to call the roll() method and each instance has its own rollID
    property that I would like to assign the setInterval ID to. Here is
    the problem.
    Since the rollID is an instance property I can't access them
    from a static class function. Is there any way to do this?
    Currently I"m just using an onEnterFrame which doesn't require me
    to use the instance properties.

    Technically yes, realistically for this class no.A
    class will probably take several hundred bytes at
    least to load, with no data of your own. So adding4
    bytes for a int is less than 1% of the total size.
    And if you are loading millions of differentclasses
    then you should rethink your design.If you don't instantiate the class when you reference
    a static variable why would you consume memory for the
    class other than the variable itself? I don't
    understand what you are talking about with the
    "millions of different classes", it's not germane to
    the question. Bottom line, referencing a static
    variable more than once will save memory.Using a class, static or by instance, requires that the class be loaded. A loaded class creates, at the very least, an instance of java.lang.Class. Any static members of the class are in addition to the storage space needed for the instance of java.lang.Class and for any internal storage needed by the JVM in addition to that.
    Thus if one has a static data member when the class is used in any way, the static data member takes storage space. However a member (non-static) does not take storage space.
    Of course the meta data for the member could take as much space as the static member so the point could be moot. Is that what you were referring to?

  • Copying Arrays - Instance Variables - Multiple Animations

    Hi All!
    Thanks so much, in advance, as always, for your assistance!
    So, here's a site I'm working on:
    http://www.mediamackenzie.com/cmix/cmix10.html
    I have 3 quick questions:
    - I tried, when I first started making this site, to load all of the artwork images into an array and then copy the array before resizing them for their specific functions (being seen as thumbnails or as full size pics.) Unfortunately, I ran into the well known issue of Array cloning only creating a pointer to the same group of items. I tried the newArray = oldArray.slice() trick, but it didn't seem to work. Finally, I just loaded the images twice into two separate arrays, and it works, but I hate this solution. Anyone got a better one?
    - I'm trying to maintain some sort of connection between the two sets of Arrays so that, for example, when someone clicks on Thumbnail 15, Fullsize Image 15 will open up but I couldn't find anything that worked. Renaming the Instance Name dynamically didn't seem to work and adding an Instance Variable dynamically doesn't seem possible either as I can't make the Class I am working with (Sprite, in this case) dynamic ahead of time. I'm sure there's a simple method for this. Any suggestions?
    - Lastly, notice how when the site opens up, the different animations seem to interfere with each other and slow each other down (they also seem to get interference from the time taken to load the image Arrays.) Anyone got any high level suggestions for how to avoid this?
    Thanks So Much!
    and Be Well
    Graham

    I'm still stuck, but close, I think. The URL: http://www.mediamackenzie.com/cmix/cmix11.html
    Here is the code from frame 1 of my Gallery MovieClip (an instance of which is created dynamically in the main timeline):
    stop();
    import fl.transitions.Tween;
    import fl.transitions.easing.*;
    var idealH = 120;
    var idealW = idealH + 50;
    var loadH = 300;
    var loadW = loadH * 2;
    var thumb = 0;
    var loadNum = 0;
    var thumby:Sprite;
    var darkStage:Sprite;
    var loadSprite:Sprite;
    var thumbArray:Array = new Array();
    var loadArray:Array = new Array();
    var bigLoad:Loader;
    var reSized:Boolean = false;
    this[thumb] = new Loader();
    this[thumb].contentLoaderInfo.addEventListener(Event.COMPLETE, thumbComplete);
    this[thumb].load(new URLRequest("images/0.png"));
    thumbArray.push(this[thumb]);
    function thumbComplete(e:Event):void {
        trace("thumbComplete");
        thumb++;
        this[thumb] = new Loader();
        this[thumb].load(new URLRequest("images/" + thumb + ".png"));
        thumbArray.push(this[thumb]);
        this[thumb].contentLoaderInfo.addEventListener(Event.COMPLETE, thumbComplete);
        this[thumb].contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, thumbError);
    function thumbError(e:IOErrorEvent):void {
        trace("thumbError");
        thumb = 0;
        thumbArray.pop();
        loadArray = thumbArray.slice();
        gotoAndStop(2);
    Now, here is the code from frame 2:
    //stop();
    addArrows();
    thumbResize();
    loadResize();
    function thumbResize():void {
    trace("thumbResize");
        for (var batch = 0; batch < Math.ceil(thumbArray.length / 8); batch++) {
            trace("batch " + batch);
            var batchSprite: Sprite = new Sprite();
            batchSprite.x = (batchSprite.x + (idealW / 1.5) + (batch * 800));
            //batchSprite.mouseEnabled = false;
            addChild(batchSprite);
            for (var row = 0; row < 2; row++) {
                trace("     row " + row);
                for (var col = 0; col < 4; col++) {
                    trace("          col " + col);
                    trace("               thumb " + thumb);
                    //If the width of the image is greater than the ideal width, OR the height is greater than the ideal height...
                    if ( thumbArray[thumb].content.width > idealW || thumbArray[thumb].content.height > idealH) {
                        //And if the width of the image is greater than the height, apply Scaler 1...
                        if ( thumbArray[thumb].content.width > thumbArray[thumb].content.height ) {
                            //Scaler 1 is the ratio of the ideal width to the image width
                            var scaler1 = idealW / thumbArray[thumb].content.width;
                            trace("               scaler1 = " + scaler1);
                            //Apply Scaler 1 to both the width and height of the image
                            thumbArray[thumb].content.scaleX = thumbArray[thumb].content.scaleY = scaler1;
                            trace("               image width:" + thumbArray[thumb].content.width);
                            trace("               image height:" + thumbArray[thumb].content.height);
                            //Otherwise, apply Scaler 2
                        } else {
                            //Scaler 2 is the ratio of the ideal width to the image height
                            var scaler2 = idealW / thumbArray[thumb].content.height;
                            trace("               scaler2 = " + scaler2);
                            //Apply Scaler 2 to both the width and height of the image
                            thumbArray[thumb].content.scaleX = thumbArray[thumb].content.scaleY = scaler2;
                            trace("               image width:" + thumbArray[thumb].content.width);
                            trace("               image height:" + thumbArray[thumb].content.height);
                        //Otherwise... (that is, the image width and height are in both cases less than the ideal)
                    } else {
                        //And if the width of the image is greater than the heigh, apply Scaler 3
                        if ( thumbArray[thumb].content.width > thumbArray[thumb].content.height ) {
                            //Scaler 3 is the ratio of the ideal width to the image width
                            var scaler3 = idealW / thumbArray[thumb].content.width;
                            trace("               scaler3 = " + scaler3);
                            //Apply Scaler 3 to both the width and height of the image
                            thumbArray[thumb].content.scaleX = thumbArray[thumb].content.scaleY = scaler3;
                            trace("               image width:" + thumbArray[thumb].content.width);
                            trace("               image height:" + thumbArray[thumb].content.height);
                        } else {
                            //Scaler 4 is the ratio of the ideal width to the image height
                            var scaler4 = idealW / thumbArray[thumb].content.height;
                            trace("               scaler4 = " + scaler4);
                            //Apply Scaler 4 to both the width and height of the image
                            thumbArray[thumb].content.scaleX = thumbArray[thumb].content.scaleY = scaler4;
                            trace("               image width:" + thumbArray[thumb].content.width);
                            trace("               image height:" + thumbArray[thumb].content.height);
                    thumbArray[thumb].content.x = - (thumbArray[thumb].content.width / 2);
                    thumbArray[thumb].content.y = - (thumbArray[thumb].content.height / 2);
                    thumby = new Sprite();
                    thumby.addChild(thumbArray[thumb]);
                    thumby.y = (row * (idealW + (idealW / 8)));
                    thumby.x = (col * (idealW + (idealW / 8)));
                    thumby.buttonMode = true;
                    thumby.useHandCursor = true;
                    thumby.addEventListener(MouseEvent.CLICK, enLarge);
                    batchSprite.addChild(thumby);
                    thumb++;
    function loadResize():void {
        trace("loadResize");
        for (var ex = 0; ex < loadArray.length; ex++) {
            //If the width of the image is greater than the ideal width, OR the height is greater than the ideal height...
            if ( loadArray[loadNum].content.width > loadW || loadArray[loadNum].content.height > loadH) {
                //And if the width of the image is greater than the height, apply Scaler 1...
                if ( loadArray[loadNum].content.width > loadArray[loadNum].content.height ) {
                    //Scaler 1 is the ratio of the ideal width to the image width
                    var scaler1 = loadW / loadArray[loadNum].content.width;
                    //Apply Scaler 1 to both the width and height of the image
                    loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler1;
                    //Otherwise, apply Scaler 2
                } else {
                    //Scaler 2 is the ratio of the ideal width to the image height
                    var scaler2 = loadW / loadArray[loadNum].content.height;
                    //Apply Scaler 2 to both the width and height of the image
                    loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler2;
                //Otherwise... (that is, the image width and height are in both cases less than the ideal)
            } else {
                //And if the width of the image is greater than the heigh, apply Scaler 3
                if ( loadArray[loadNum].content.width > loadArray[loadNum].content.height ) {
                    //Scaler 3 is the ratio of the ideal width to the image width
                    var scaler3 = loadW / loadArray[loadNum].content.width;
                    //Apply Scaler 3 to both the width and height of the image
                    loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler3;
                } else {
                    //Scaler 4 is the ratio of the ideal width to the image height
                    var scaler4 = loadW / loadArray[loadNum].content.height;
                    //Apply Scaler 4 to both the width and height of the image
                    loadArray[loadNum].content.scaleX = loadArray[loadNum].content.scaleY = scaler4;
            loadArray[loadNum].content.x = - (loadArray[loadNum].content.width / 2);
            loadArray[loadNum].content.y = - (loadArray[loadNum].content.height / 2);
            loadNum++;
    function addArrows():void {
        trace("addArrows");
        var batches =  Math.ceil(thumbArray.length / 8);
        var m = 0;
        trace("batches = " + batches);
        if (batches > 1) {
            for (var k = 1; k < batches; k++) {
                var triW = 20;
                var startX = (((800 - triW) * k) + (triW * m));
                var startY = (idealW / 2);
                var tri:Sprite = new Sprite();
                tri.graphics.beginFill(0xFFFFFF);
                tri.graphics.moveTo(startX, startY);
                tri.graphics.lineTo(startX, (startY + triW));
                tri.graphics.lineTo((startX + triW), (startY + (triW/2)));
                tri.graphics.lineTo(startX, startY);
                tri.graphics.endFill();
                tri.buttonMode = true;
                tri.useHandCursor = true;
                tri.addEventListener(MouseEvent.CLICK, moveLeft);
                addChild(tri);
                var tri2:Sprite = new Sprite();
                var startX2 = (startX + (triW * 2));
                tri2.graphics.beginFill(0xFFFFFF);
                tri2.graphics.moveTo(startX2, startY);
                tri2.graphics.lineTo(startX2, (startY + triW));
                tri2.graphics.lineTo((startX2 - triW), (startY + (triW / 2)));
                tri2.graphics.lineTo(startX2, startY);
                tri2.graphics.endFill();
                tri2.buttonMode = true;
                tri2.useHandCursor = true;
                tri2.addEventListener(MouseEvent.CLICK, moveRight);
                addChild(tri2);
                m++;
    function moveLeft(event:MouseEvent):void {
        var leftTween:Tween = new Tween(this, "x", Regular.easeOut, this.x, (this.x - 800), .5, true);
    function moveRight(event:MouseEvent):void {
        var rightTween:Tween = new Tween(this, "x", Regular.easeOut, this.x, (this.x + 800), .5, true);
    function enLarge(event:MouseEvent):void {
        darkStage = new Sprite();
        darkStage.graphics.beginFill(0x000000, .75);
        darkStage.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
        darkStage.addEventListener(MouseEvent.CLICK, reMove);
        darkStage.buttonMode = true;
        darkStage.useHandCursor = true;
        parent.addChild(darkStage);
        var nmbr = thumbArray.indexOf(event.currentTarget);
        bigLoad = new Loader();
        bigLoad = loadArray[nmbr];
        trace("bigLoad: " + bigLoad);
        loadSprite = new Sprite();
        loadSprite.addChild(bigLoad);
        loadSprite.x = (stage.stageWidth / 2);
        loadSprite.y = (stage.stageHeight / 2);
        loadSprite.addEventListener(MouseEvent.CLICK, reMove);
        loadSprite.buttonMode = true;
        loadSprite.useHandCursor = true;
        parent.addChild(loadSprite);
    function reMove(event:MouseEvent):void {
        parent.removeChild(darkStage);
        parent.removeChild(loadSprite);
    The function enLarge is the source of the issue (I want the enlarged image to show up and it's not.)
    Please help if you can!
    Thanks,
    Graham

  • Using instance variables

    Hi,
    I am currently evaluating this tool for a specific user group. I had a question in mind :
    In a typical workflow which involves database connections (i.e. inserting data in a database and displayign data) do you think we should pass data between various activities and users using instance variables or do you think we should retrieve data from the tables every time for display etc

    I would suggest get the data from the database first time and then store it in instance variables. Whenever, you need to update any values in the database from a particular activity, make a call to database to update it with the values from instance variables.
    For displaying, use instance variables. You do not need to get fresh data from database for each activity, unless you think that data in database keeps changing for that particular records every day.
    Regards
    Right Chord

  • Using Class and Constructor to create instances on the fly

    hi,
    i want to be able to create instances of classes as specified by the user of my application. i hold the class names as String objects in a LinkedList, check to see if the named class exists and then try and create an instance of it as follows.
    the problem im having is that the classes i want to create are held in a directory lower down the directory hierarchy than where the i called this code from.
    ie. the classes are held in "eccs/model/behaviours" but the VM looks for them in the eccs directory.
    i cannot move the desired classes to this folder for other reasons and if i try to give the Path name to Class.forName() it will not find them. instead i think it looks for a class called "eccs/model/behaviours/x" in the eccs dir and not navigate to the eccs/model/behaviours dir for the class x.
    any ideas please? heres my code for ye to look at in case im not making any sense:)
    //iterator is the Iterator of the LinkedList that holds all the names of the
    //classes we want to create.
    //while there is another element in the list.
    while(iterator.hasNext())
    //get the name of the class to create from the list.
    String className = (String) iterator.next();
    //check to see if the file exists.
    if(!doesFileExist(className))
    System.out.println("File cannot be found!");
    //breake the loop and move onto the next element in the list.
    continue;
    //create an empty class.
    Class dynamicClass = Class.forName(className);
    //get the default constructor of the class.
    Constructor constructor = dynamicClass.getConstructor(new Class[] {});
    //create an instance of the desired class.
    Behaviour beh = (Behaviour) constructor.newInstance(new Object[] {});
    private boolean doesFileExist(String fileName)
    //append .class to the file name.
    fileName += ".class";
    //get the file.
    File file = new File(fileName);
    //check if it exists.
    if(file.exists())
    return true;
    else
    return false;
    }

    ok ive changed it now to "eccs.model.behaviours" and it seems to work:) many thanks!!!
    by the following you mean that instead of using the method "doesFileExist(fileName)" i just catch the exception and throw it to something like the System.out.println() ?
    Why don't you simply try to call Class.forName() and catch the exception if it doesn't exist? Because as soon as you package up your class files in a jar file (which you should) your approach won't work at all.i dont think il be creating a JAR file as i want the user to be able to create his/her own classes and add them to the directory to be used in the application. is this the correct way to do this??
    again many thanks for ye're help:)

  • About "method", "instance variable" and "constructor"

    Does a method need to be initialise?? if yes, how to write the code?
    for example,is it:
    public String mymethod( String args[]); ?
    public double mymethod2 (); ?
    what is the meaning of "instance variable" and "constructor"?
    Please help.....THANKS!

    Previously posted to this OP:
    Read the Java Tutorial: Learning the Java Language.
    http://java.sun.com/docs/books/tutorial/java/index.html
    � {�                                                                                                                                                                                                                                                                                                   

  • What's the difference between global variables and instance variables?

    hi im just a biginner,
    but what is the difference between these two?
    both i declare them above the constructor right.
    and both can access by any method in the class but my teacher said
    global variables are not permitted in java....
    but i don't know what that means....and i got started to confuse these two types,,
    im confusing.......
    and why my teacher said declaring global variables is not permitted,,,,,,
    why.....

    instance variables are kindof like Global variables. I'm not surprised you are confused.
    The difference is not in how they are declared, but rather in how they are used.
    There are two different "styles" of programming
    - procedural programming.
    - object oriented programming.
    Global variables are a term from Procedural programming.
    In this style of programming, you have only one class, and one "main" procedure. You only create one instance of the class, and then "run" it.
    There is one thread of control, which goes through various methods/procedures to accomplish your task.
    In this style of programming instance variables ARE "global" variables. They are accessible to all methods. There is only one instance of the class, and thus only one instance of the variables.
    Global variables are "bad" BECAUSE you can change them in any method you like. Even from places that shouldn't have to. Also if you use the same name as a global variable and a local variable, you can cause great trouble. This can lead to very subtle bugs, as the procedures interact in ways you don't expect.
    The preferred method in procedural programming is to pass the values as parameters to the methods, and only refer to the parameters, and local variables. This means that you can track exactly what your method is doing, and what it affects. It makes it simpler to understand. If you use global variables in your methods, it becomes harder to understand.
    So when are instance variables not global variables?
    When you are actually using the class as an Object, rather than just a program to run. If you are creating multiple instances of an object, all with different values for their instance variables, then they are not global variables. For instance you declare a Person object with an attribute "firstname". Your "main" program then creates many instances of the Person object, each with their own "firstname"
    I guess at the end of all this, it comes down to definitions.
    Certainly you can write procedural code in java. You can treat your instance variables, for all intents and purposes like global variables.
    I can only think to show a sort of example
    public class Test1
       User[] users;
       public void printUsers(){
         // loop through and print all the users
         // uses a global variable
          for(int i=0; i<users.length; i++){
            users.printUser();
    public void printUsers(User[] users){
    // preferred method - pass it the info it needs to do the job
    for(int i=0; i<users.length; i++){
    users[i].printUser();
    public Test1(){
    User u1 = new User("Tom", 20);
    User u2 = new User("Dick", 42);
    User u3 = new User("Harry", 69);
    users = new User[3];
    users[0] = u1;
    users[1] = u2;
    users[2] = u3;
    printUsers();
    printUsers(users);
    public static void main(String[] args)
    new Test1();
    class User{
    String firstName;
    int age;
    public User(String name, int age){
    this.firstName = name;
    this.age = age;
    public void printUser(){
    // here they are used as instance variables and not global variables
    System.out.println(firstName + " Age: " + age);
    Shit thats a lot of typing, and I'm not even sure I've explained it any good.
    Hope you can make some sense out of this drivel.
    Cheers,
    evnafets

  • Parsing XML and Storing values in instance variable

    hi,
    i'm new to XML.
    here i'm trying to parse an XML and store their element data to the instance variable.
    in my main method i'm tried to print the instance variable. but it shows "" (ie it print nothing ).
    i know the reason, its becas of the the endElement() event generated and it invokes the characters() and assigns "" to the instance variable.
    my main perspective is to store the element data in instance variable.
    thanks in advance.
    praks
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    public class mysax extends DefaultHandler
         String ctelement;
         CharArrayWriter contents;
         String vname1,vrcbreg1,vaddress1,vcountry1,vtelephone1,vfax1;
         String vname,vrcbreg,vaddress,vcountry,vtelephone,vfax;
         public mysax()
              vname1 = null;
              vrcbreg1 = null;
              vaddress1 = null;
              vcountry1 = null;
              vtelephone1 = null;
              vfax1 = null;
              contents= new CharArrayWriter();
         public void doparse(String url) throws Exception
              SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    ParserAdapter pa = new ParserAdapter(sp.getParser());
    pa.setContentHandler(this);
    pa.parse(url);          
         public void startElement(String namespace,String localName,String qName,Attributes atts)
              ctelement = localName;     
         public void endElement(String uri,String localName,String qName) throws SAXException
         public void characters(char[] ch,int start, int length) throws SAXException
              try
                   if(ctelement.equals("name"))
                        vname = new String (ch,start,length);
                        System.out.println("The method "+vname1);
              }catch (Exception e)
                   System.out.println("The exception "+e);
         public static void main(String args[])
              try
              mysax ms = new mysax();
              ms.doparse(args[0]);
              System.out.println("the contents name "+ms.vname1);
              catch(Exception e)
                   System.out.println("this is exception at main" +e);
    my XML looks like
    <coyprofile_result>
    <company>     
    <name>abcTech</name>
    <rcbreg>123456789</rcbreg>
    <address>Singapore</address>
    <country>sg</country>
    <telephone>123456</telephone>
    <fax>123155</fax>
    </company>
    </coyprofile_result>

    I believe that the problem has to do with the value you assign to ctelement. You are assigning the value of localName to ctElement, however for the element: <name>...</name> the localname is empty string i.e. "", but qName equals "name". Because you are assigning empty string to ctElement, when you do the comparison in characters of ctElement to "name" it will always be false. So in startElement change it to ctElement = qName; Try it and see if it works. I have produced similar programs and it works for me.
    Hope this helps.

  • How to change value of instance variable and local variable at run time?

    As we can change value at run time using debug mode of Eclipse. I want to do this by using a standalone prgram from where I can change the value of a variable at runtime.
    Suppose I have a class, say employee like -
    class employee {
    public String name;
    employee(String name){
    this.name = name;
    public int showSalary(){
    int salary = 10000;
    return salary;
    public String showName()
    return name;
    i want to change the value of instance variable "name" and local variable "salary" from a stand alone program?
    My standalone program will not use employee class; i mean not creating any instance or extending it. This is being used by any other calss in project.
    Can someone tell me how to change these value?
    Please help
    Regards,
    Sujeet Sharma

    This is the tutorial You should interest in. According to 'name' field of the class, it's value can be change with reflection. I'm not sure if local variable ('salary') can be changed - rather not.

  • JSP and Instance Variables

    I have some questions about JSP presentation (Interactive Component Call in Screenflow):
    - Only BPM Objects are possible to be mapped in JSP?
    - Is possible to map two or more BPM Objects to the JSP?
    - What is the difference of mapping using the variable "attributes" in argument mapping and the option "Select BPM object variable" in main task of Interactive Component Call activity?

    I seem to be having a similar problem.
    If I include this fragment, for an instance variable called "contacts" which is a BPMObject of type "ITSSContactRequest".
    <%
    Object r = request.getAttribute("contacts");               
    Class cl = r.getClass();
    out.println(cl.getName());
    %>
    I get the following output:
    xobject.ITSSContactManagement.ITSSContactRequest
    and I can access the object via reflection:
    <%
    Object r = request.getAttribute("contacts");               
    Class cl = r.getClass();
    out.println(cl.getName());     
    Method getGeneralContacts = cl.getMethod("getGeneralContacts", null);               
    Object rv = getGeneralContacts.invoke(r);
    %>
    and access the rv variable accordingly.
    However, if I try and cast the variable directly:
    <%
    Object r = request.getAttribute("contacts");
    Class cl = r.getClass();               
    out.println(cl.getName());
    xobject.ITSSContactManagement.ITSSContactRequest rq = (xobject.ITSSContactManagement.ITSSContactRequest)r;
    %>
    I get the following error message:
    "The task could not be successfully executed. Reason: 'fuego.web.execution.exception.InternalForwardException: UnExpected error during internal forward process.'.
    See log file for more information [Error code: workspace-1258985548580] "
    The same error occurs if I try and import the object via
    <%@ page import="xobject.ITSSContactManagement.ITSSContactRequest" %>
    Thanks for any help.

  • Is it possible to override constructor and instance initializer?

    In the source below, I found that all 4 System.out.println() messages are printed.
    Is it possible to have the constructor and instance intializer in ClassC overrides that of ClassB?
    import java.util.*;
    class ClassB {
              System.out.println("Hello");     
         ClassB() {
              System.out.println("HaHa");     
    class ClassC extends ClassB {
              System.out.println("Hello1");     
         ClassC() {
              System.out.println("HaHa1");     
    public class Test1 {
         public static void main(String[] args) {
              ClassC c = new ClassC();
    }

    You can't override an instance initializer, no. And when you create an object, some constructor of each of its superclasses must be called to do the creating. In your example, it's the default constructor of ClassB that's called. ClassC's constructor must call some constructor of ClassB.

  • Inheritance and private instance variables

    I've been reading a Java book. It says you should normally make your instance variables private and use getter/setter methods on them, but if you create a superclass, you have to make those variables public (or default?) to inherit them in the subclasses, right? And you can't redefine the variables as private in the subclass, can you?
    I'm a little confused on this point. Thanks for any light anyone could shed on this.
    =====
    Nevermind...I think I figured it out!
    Message was edited by:
    NovaKane

    Thanks to both of you for your responses. I think I've pretty much done what you did, Anan, in this little test program.
    public class Animal
       private String name=null;
       public void setName(String n)
          name=n;
       public String getName()
         return name;
       public void makeSound()
    public class Dog extends Animal
       public void makeSound()
          if (getName() !=null)
             System.out.println(getName()+" says, \"Bow Wow!\"");
          else
             System.out.println("I don't have a name...but \"Bow Wow!\"");
    public class Cat extends Animal
       public void makeSound()
          if (getName() != null)
             System.out.println(getName()+" says, \"Meow!\"");
          else
             System.out.println("I have no name...but, \"Meow!\"");
    import java.util.*;
    public class Test
       public static void main(String[] vars)
            ArrayList<Animal> animals = new ArrayList<Animal>();
            Animal d = new Dog();
            Animal c = new Cat();
            d.setName("Fido");
            c.setName("Fluffy");
            animals.add(d);
            animals.add(c);
            for (Animal a : animals)
                a.makeSound();
    }The "name" instance variable is private, but I can get at it through the getter/setter methods of the superclass, which are public. I should NOT be able to say something like...
    d.name="Fido";Right?

  • Constructor and Class constructor

    Hi all
    Can any one explain me the functionality about Constructor and class constructor??
    As well as normal methods, which you call using CALL METHOD, there are two special methods
    called CONSTRUCTOR and CLASS_CONSTRUCTOR, which are automatically called when you
    create an object (CONSTRUCTOR) or when you first access the components of a class
    (CLASS_CONSTRUCTOR)
    I have read the above mentioned document from SAP Documents but i found it bit difficult to understand can any one please help me on this??
    Thanks and Regards,
    Arun Joseph

    Hi,
    Constructor
    Implicitly, each class has an instance constructor method with the reserved name constructor and a static constructor method with the reserved name class_constructor.
    The instance constructor is executed each time you create an object (instance) with the CREATE OBJECT statement, while the class constructor is executed exactly once before you first access a class.
    The constructors are always present. However, to implement a constructor you must declare it explicitly with the METHODS or CLASS-METHODS statements. An instance constructor can have IMPORTING parameters and exceptions. You must pass all non-optional parameters when creating an object. Static constructors have no parameters.
    Class Constructor
    The static constructor is always called CLASS_CONSTRUCTER, and is called autmatically before the clas is first accessed, that is before any of the following actions are executed:
    Creating an instance using CREATE_OBJECT
    Adressing a static attribute using ->
    Calling a ststic attribute using CALL METHOD
    Registering a static event handler
    Registering an evetm handler method for a static event
    The static constructor cannot be called explicitly.
    For better understanding check the following code:
    REPORT  z_constructor.
          CLASS cl1 DEFINITION
    CLASS cl1 DEFINITION.
      PUBLIC SECTION.
        METHODS:
          add,
          constructor IMPORTING v1 TYPE i
                                v2 TYPE i,
          display.
        CLASS-METHODS:
         class_constructor.
      PRIVATE SECTION.
        DATA:
        w_var1   TYPE i,
        w_var2   TYPE i,
        w_var3   TYPE i,
        w_result TYPE i.
    ENDCLASS.                    "cl1 DEFINITION
          CLASS cl1 IMPLEMENTATION
    CLASS cl1 IMPLEMENTATION.
      METHOD constructor.
        w_var1 = v1.
        w_var2 = v2.
      ENDMETHOD.                    "constructor
      METHOD class_constructor.
        WRITE:
        / 'Tihs is a class or static constructor.'.
      ENDMETHOD.                    "class_constructor
      METHOD add.
        w_result = w_var1 + w_var2.
      ENDMETHOD.                    "add
      METHOD display.
        WRITE:
        /'The result is =  ',w_result.
      ENDMETHOD.                    "display
    endclass.
    " Main program----
    data:
      ref1 type ref to cl1.
    parameters:
      w_var1 type i,
      w_var2 type i.
      start-of-selection.
      create object ref1 exporting v1 = w_var1
                                  v2 = w_var2.
       ref1->add( ).
       ref1->d isplay( ).
    Regards,
    Anirban Bhattacharjee

  • Servlets and their instance variables

    I understand that for every request to a servlet, a new thread handles those requests. So it's one request, one thread. But how about instance variables of a servlet class? Are they also one instance variable per thread/request or just like the servlet, one instance?

    hi, its exactly as you expect - one instance at all. all threads are working with one intance. you can indeed finetune the number of instances of a servlet using the
    <load-on-startup/>tag in the web.xml file, but its up to container if multiple thread will be using many instances.
    you can also implement the (deprecated) SingleThreadedModel interface which flags the container not to share that servlet instance to other threads. But this shall not be used in productive environments.
    so its always a good idea to put your business impleementation to another class and only use the servlets to connect your business implementation to http like
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
       new MyBusinessLogic().perform(request.getInputStream(), response.getOutputStream());
    }

  • Classes and Constructor

    If i have to build a class with a constructor that prompts user to input X integers and store them into the array registers how do I do it? Couple specific questions:
    1. What part of program contains the instructions for user to input data?Is it in the control program or in the object?
    2. If I do the array in the object does the array int[] myarray = new int[10]have to be before constructor definition?
    3. Does the scanner belong in the object or in the control program?
    I appreciate any info provided. I do not expect this assignment to be done for me, just looking to be educated.

    Sarugaki wrote:
    If i have to build a class with a constructor that prompts user to input X integers and store them into the array registers how do I do it?Personally, I think that's sloppy design. Constructors shouldn't ask for user input, IMHO. A constructor should end with an object in a valid state, and that's difficult to do when you're dependent on the user inputting meaningful information. It also creates a (partial) dependency on a particular usage pattern. You can mitigate this by throwing an exception, but still.
    Couple specific questions:
    1. What part of program contains the instructions for user to input data?Is it in the control program or in the object?Eh? There are library classes that can query user input. You can write a class to call those classes. If you call them in the constructor, then then object has the code (well, the class does). I'm not sure I understand your question.
    2. If I do the array in the object does the array int[] myarray = new int[10]have to be before constructor definition?If you put that line inside of the constructor, then myarray will be a local variable that goes away when the constructor is finished. You probably mean for it to be a field of the class (thus, declared outside of the constructor).
    3. Does the scanner belong in the object or in the control program?By "control program" I presume you mean the class with the main() method.
    Personally, I think it makes more sense to do I/O outside of the constructor, and so, I'd put it in the main() method (or some other method).
    Another option might be, for example, to create a static method in the class whose objects you are creating. This static method would create a Scanner, get user input, and then use that input (if it's valid) to create an object. If the input is invalid, it would return null. In this case, the Scanner would go in the class of the the object in question, and not in that thing which you're calling the "control program".
    "You have been selected to play on the game grid." Extra points to whomever can spot that reference (and why I mentioned it).
    ah, too slow again
    Edited by: paulcw on Apr 27, 2008 3:04 PM

Maybe you are looking for