Calling up class methods

I suffer problems understanding how to call up class methods from within my programs and would like to see further examples of coding and a lending hand with the problem below, program one ProductClass works out stock item lines of a product, the program then needs to ask for the StaticProduct Class(the second program attached) to check for a valid barcode length and for how many odds and even numbers are within it a valid barcode would be 5000127062092
I would very much appreciate some help:
* This is a program to Enter and check product codes and prices
* and give a summary of values at the end
* @author (Jeffrey Jones)
* @version (version 2 5th April 2003)
public class ProcessProduct
public static void main(String args[])
StaticProduct Product = new StaticProduct();
//declare variables
String manuf;
String name;
int sLength;
String p;
String barcode;
int price;
int quantity;
int totalPrice=0;
int transactions=1;
int totalQuantity=0;
int totalValue=0;
int averageCost=0;
//Input Details
System.out.print("Enter Product Manufacturer : ");
manuf = UserInput.readString();
//start of while loop checking for 0 to exit loop
while (!manuf.equals("0"))
System.out.print("Enter Product Name : ");
name = UserInput.readString();
System.out.print("Enter Bar Code : ");
barcode = UserInput.readString();
//check for invalid data
if (StaticProduct.isValidBarcode(barcode))
{barcode = new code();
                    p = new Product("manuf","name","quantity","price");
                    }//closing bracket of if
else
{//error handling
}//closing bracket of if
//check for quantity input and errors
System.out.print("Enter Quantity : ");
quantity = UserInput.readInt();
if (quantity<=0)
{ System.out.print(" Error, invalid value ");
System.exit(0);
}// check for invalid entries
System.out.print("Enter Price :");
price = UserInput.readInt();
//check for price input and errors
if (price<=0)
{ System.out.print(" Error, invalid value ");
}// check for invalid entries
//total price value
totalPrice=price*quantity;
//Output of correctly inputted data
System.out.println(manuf+":"+name+":"+barcode+":"+price);
System.out.println(quantity+" @ "+price+" = "+totalPrice);
//update variables quantities
//update total quantity
totalQuantity = (totalQuantity + quantity);
//keep count of total value
totalValue = (totalValue + totalPrice);
//keep count of totqal no of transactions
transactions = (transactions++);
//Input Details
System.out.print("Enter Product Manufacturer : ");
manuf = UserInput.readString();
}//closure of loop
//display final totals
System.out.println("Transactions: "+transactions);
System.out.println("Total quantity: "+totalQuantity);
System.out.println("Total value: "+totalValue);
System.out.println("Average Cost: "+totalValue/totalQuantity);
System.exit(0);
}//closing bracket input and output of data
}//end class
* Write a description of class StaticProduct here.
* @author Jeffrey Jones
* @version 1 1st April 2003
public class StaticProduct
* isValidBarcode method - to check for correct barcode and length
* @return boolean
public static boolean isValidBarcode(String barcode) {
barcode = new barcode();
// validateBarcode length
if ( barcode.length() != 13 ) {
System.out.println("Invalid barcode " + barcode + " not 13 characters");
return false;
}//if
for ( int i = 0; i < barcode.length(); i++ ){// Check every char a digit
if ( ! Character.isDigit( barcode.charAt(i) ) ){
System.out.println("Invalid barcode " + barcode + " not all digits");
return false;
}//if
}//endfor
int sum1 = 0; // Sum first + third + etc.
for ( int i = 0; i < barcode.length() - 1; i += 2 ){
sum1 += barcode.charAt(i) - '0';
}//endfor
int sum2 = 0; // Sum second + fourth + etc.
for ( int i = 1; i < barcode.length() - 1; i += 2 ){
sum2 += barcode.charAt(i) - '0';
}//endfor
int check = sum1 + 3 * sum2; // 1st sum + three times 2nd sum.
check = check % 10; // Remainder on division by 10.
if ( check != 0 ){
check = 10 - check;
}//endif
if (check != barcode.charAt(12) - '0'){
System.out.println("Invalid barcode " + barcode + " check digit error");
}//endif
return ( check == barcode.charAt(12) - '0' );
}//end isValidBarcode
public static void main(String[] argv) {
System.out.println(isValidBarcode("1234567890123"));
System.out.println(isValidBarcode("123"));
System.out.println(isValidBarcode(""));
System.out.println(isValidBarcode("5018374496652"));
}//end main
}//end class

Read through your text book or some java tutorials from this site to understand what classes are, what are methods, etc.
Your program is full of wrong initializations (as you rightly said you dont understand how to call up class method I would add that you dont understand how to call classes and what do they return e.g.
You have declared
String p;
then you go ahead and do this
p = new Product("manuf","name","quantity","price"); This is syntax for calling a class is this class returning a String? :s
Please go through the basics of Object Oriented Programming and then start with the coding part else you will face such very many difficulties and waste more time of yours in just coding with no results.
Look for the tutorials on this site and read through them and do example as given in them.

Similar Messages

  • Is it possible to call a class method using pattern in ABAP editor.

    Hi,
         Is it possible to call a class method using pattern in ABAP editor.
    Thank U for Ur time.
    Cheers,
    Sam

    Yes,
    Click patterns.
    Then choose Abap objects patterns.
    Click on the Tick
    It will give a new screen
    Here Give the name of the class first.
    Then the object (instance of the calss)
    And finally the method ..
    it will give you the pattern
    Hope this helps.

  • Code to call friends class method

    Hello,
    Please can someone help me with friends class method call. in global classes
    Thanks
    Megh
    Moderator message: please search for available information/documentation before asking.
    Edited by: Thomas Zloch on Nov 2, 2010 5:29 PM

    What is your exact problem?
    The class whose private and protected section you want to use, needs declaration of its friends. You do it in Friends tabstrip. All these classes are allowed then to access these "hiden" sections from outside of the class. Below example how it works with local classes. For global ones the principle stays the same
    CLASS lcl_main DEFINITION DEFERRED.
    CLASS lcl_other DEFINITION FRIENDS lcl_main. "only LCL_MAIN can use may hiden sections
      PROTECTED SECTION.
        METHODS prot_meth.
      PRIVATE SECTION.
        METHODS priv_meth.
    ENDCLASS.                  
    CLASS lcl_other IMPLEMENTATION.
      METHOD prot_meth.
        WRITE / 'This is protected method of class lcl_other'.
      ENDMETHOD.                    "prot_meth
      METHOD priv_meth.
        WRITE / 'This is private method of class lcl_other'.
      ENDMETHOD.                    "priv_meth
    ENDCLASS.                   
    CLASS lcl_main DEFINITION.
      PUBLIC SECTION.
        METHODS call_friends_methods.
      PRIVATE SECTION.
        DATA mr_my_friend TYPE REF TO lcl_other.
    ENDCLASS.                  
    CLASS lcl_main IMPLEMENTATION.
      METHOD call_friends_methods.
        CREATE OBJECT mr_my_friend.
        mr_my_friend->prot_meth( ).
        mr_my_friend->priv_meth( ).
      ENDMETHOD.                   
    ENDCLASS.           
    START-OF-SELECTION.
      DATA gr_main TYPE REF TO lcl_main.
      CREATE OBJECT gr_main.
      gr_main->call_friends_methods( ).
    Regards
    Marcin

  • Calling ABAP class methods from JAVA application

    Hi All,
    I want to fetch ITS related information (SITSPMON Tcode) in my JAVA application. But i didnt find much BAPIs for the same. While debugging I came accross few class methods with help of which I can get the required information. So is there any way we can call and execute methods of ABAP classes through java application?
    for e.g. I want to call GET_VERSION method of CL_ITSP_UTIL class.
    Thanks,
    Arati.

    Hi,
    Yes, as per my knowledge the only way to interact is using BAPI exposed as RFCs. So try to invoke those class methods in one CUSTOM BAPI and expose that BAPI as RFC and consume that RFC to get those details.
    Regards,
    Charan

  • Dynamic Call Function/Class Method

    Hi,
    I have a requirement for which I need your help.
    I want to Call a Method dynamically inside a program. how to do it?
    My another quary is that how to call more than one class method dynamicaly in the program one at a time, based on certain conditions.
    All the requirements mentioned above feels awakward to me, but are they feasible. Eagerly waiting for a reply.
    Regards,
    Pulokesh
    Moderator message - Cross post locked
    Edited by: Rob Burbank on Oct 26, 2009 9:48 AM

    Hello,
    you can call a Method like this where the name of the method is concatenated.
    CONCATENATE 'SC_' me->gf_scenario '_SAVE' INTO lf_method.
      CALL METHOD me->(lf_method).
    Than I can imagine to loop over a tabele with all the Method Call to be executes un there:
    Loop at gt_meth_calls into ls_meth_call.
       ls_meth_call-object_instance->(ls_meth_call-meth_name).
    endloop.
    The table should be structured such that the first component contains a reference to the instance and the second component will be the Method name to run.

  • Call enhancement class method from Bus. workflow task

    Hi all,
    I recently enhanced a global class from SAP (add a new method). Now I would like to call it from a workflow task (ABAP Class object used in the task). So it seems that only "native" methods from the class itself can be selected for the object method of the task.
    Same issue if I try to call it via secondary methods options...
    Last idea I have before the repair is: retrieve the instance saved into the WF container via a custom class interfacing IF_IFS_SWF_CONTAINER_EXIT (program exit) and call the enhanced method from the method proposed in this interface.
    Maybe someone had the same issue? Anyone could help or propose solution?
    Many thanks in advance for your help,
    KR,
    Olivier

    I think it might qualify for an OSS message.
    There was simmilar note for BADIs which was corrected: https://service.sap.com/sap/support/notes/1156392
    CL_SWF_UTL_DEF_SERVICES which is used in PFTC to determine callable methods doesn't include enhancements when calling  function SEO_CLASS_TYPEINFO_GET (parameter WITH_ENHANCEMENTS is default FALSE)

  • How to call inner class method in one java file from another java file?

    hello guyz, i m tryin to access an inner class method defined in one class from another class... i m posting the code too wit error. plz help me out.
    // test1.java
    public class test1
         public test1()
              test t = new test();
         public class test
              test()
              public int geti()
                   int i=10;
                   return i;
    // test2.java
    class test2
         public static void main(String[] args)
              test1 t1 = new test1();
              System.out.println(t1.t.i);
    i m getting error as
    test2.java:7: cannot resolve symbol
    symbol : variable t
    location: class test1
              System.out.println(t1.t.geti());
    ^

    There are various ways to define and use nested classes. Here is a common pattern. The inner class is private but implements an interface visible to the client. The enclosing class provides a factory method to create instances of the inner class.
    interface I {
        void method();
    class Outer {
        private String name;
        public Outer(String name) {
            this.name = name;
        public I createInner() {
            return new Inner();
        private class Inner implements I {
            public void method() {
                System.out.format("Enclosing object's name is %s%n", name);
    public class Demo {
        public static void main(String[] args) {
            Outer outer = new Outer("Otto");
            I junior = outer.createInner();
            junior.method();
    }

  • Unable to call Java class method within Embedding Java Activity in BPEL

    Hi ,
    I have written Java Class named 'Class3' .
    When I am creating and trying to call these classes whithin Embedding Java Activity , compile time error is coming. Compiler is not finding class . Error message is like this one.
    uildfile: C:\Oracle\Middleware\jdeveloper\bin\ant-sca-compile.xml
    scac:
    [scac] Validating composite : 'C:\JDeveloper\mywork\Application7\Embedded15\composite.xml'
    [scac] C:\JDeveloper\mywork\Application7\Embedded15\SCA-INF\bpel\BPELEmbedded15\src\orabpel\bpelembedded15\ExecLetBxExe0.java:73: cannot find symbol
    [scac] symbol : class Class3
    [scac] location: class orabpel.bpelembedded15.ExecLetBxExe0
    [scac] C:\JDeveloper\mywork\Application7\Embedded15\SCA-INF\bpel\BPELEmbedded15\src\orabpel\bpelembedded15\ExecLetBxExe0.java:73: cannot find symbol
    [scac] symbol : class Class3
    [scac] location: class orabpel.bpelembedded15.ExecLetBxExe0
    [scac] Note: C:\JDeveloper\mywork\Application7\Embedded15\SCA-INF\bpel\BPELEmbedded15\src\orabpel\bpelembedded15\BPEL_BIN.java uses unchecked or unsafe operations.
    [scac] Note: Recompile with -Xlint:unchecked for details.
    [scac] FATAL_ERROR: location {ns:composite/ns:component[@name='BPELEmbedded15']}(20,36): Failed to compile bpel generated classes.
    [scac] failure to compile the generated BPEL classes for BPEL process "BPELEmbedded15" of composite "default/Embedded15!1.0"
    [scac] The class path setting is incorrect.
    [scac] Ensure that the class path is set correctly. If this happens on the server side, verify that the custom classes or jars which this BPEL process is depending on are deployed correctly. Also verify that the run time is using the same release/version.
    [scac]
    BUILD FAILED
    C:\Oracle\Middleware\jdeveloper\bin\ant-sca-compile.xml:264: Java returned: 1 Check log file : C:\JDeveloper\mywork\Application7\Embedded15\SCA-INF\classes\scac.log for errors
    Total time: 8 seconds
    I am creating Class3 directly in Application Resources folder indide Project Folder in Jdeveloper without creating any package. Code of the class is .......
    public class Class3 {
    public Class3() {
    super();
    public String getValue(){
    return "BBBBBBB";
    Can any one help?
    Regards
    Yogendra Rishishwar
    9867927087

    Hi ,
    In your java project frm jdev..right click and choose general and then choose deployment profiles and then choose Jar ..and then give some appropriate name(abc) and then click ok.
    Then under resources file u get a abc.deploy file right click and say deploy to jar ..u will find the jar in that director.Now include this jar in your prjct libraries.
    have a look at the link http://niallcblogs.blogspot.com/search/label/embedded%20Java

  • Calling sub class method from superclass constructure

    hi all
    i have seen a program in which a super class constructure class methods of sub class before initialization of fields in subclass ,i want how this is posibble ?
    thanks in advance

    Hear is the code n other thing i have used final variable without initialization n compiler dosen't report error
    abstract class Test
    public Test()
    System.out.println("In DemoClass Constructer");
    this.show();
    public void show()
    System.out.println("In DemoClass Show() method");
    class Sub1 extends Test
    private final float number;
    public Sub1(float n)
    this.number=n;
    System.out.println((new StringBuilder()).append("Number is==").append(number).toString());
    int j;
    public void show()
    System.out.println("In Sub1 Class Show method ");
    public class DemoClass
    public static void main(String s[])
    Sub1 obj1=new Sub1(5);
    Sub1 obj2=new Sub1(6);
    thanks for reply

  • How to call a class method from a jsp page?

    Hi all,
    i would like to create a basic jsp page in jdev 1013 that contains a button and a text field. When clicking the button, i would like to call a method that returns a string into the text field.
    The class could be something like this:
    public class Class1 {
    public String getResult() {
    return "Hello World";
    How do i go about this?
    Thanks

    Here is a sample:
    HTML><HEAD><TITLE>Test JDBC for Oracle Support</TITLE></HEAD><BODY>
    <%@ page import="java.sql.*, oracle.jdbc.*, oracle.jdbc.pool.OracleDataSource" %>
    <% if (request.getParameter("user")==null) { %>
    <FORM method="post" action="testjdbc.jsp">
    <H1>Enter connection Parameters</H1>
    <H5>Please enter host name:</H5><INPUT TYPE="text" name="hostname" value="localhost" />
    <H5>Please enter port number:</H5><INPUT TYPE="text" name="port" value="1521" />
    <H5>Service nanme:</H5><INPUT TYPE="text" name="service" value="XE" />
    <H5>Please enter username: </H5><INPUT TYPE="text" name="user" />
    <H5>Please enter password</H5><INPUT TYPE="password" name="password" />
    <INPUT TYPE="submit" />
    </FORM>
    <% } else { %>
    <%
    String hostName = request.getParameter("hostname");
    String portNumber = request.getParameter("port");
    String service = request.getParameter("service");
    String user = request.getParameter("user");
    String password = request.getParameter("password");
    String url = "jdbc:oracle:thin:" + user + "/" + password + "@//" + hostName + ":" + portNumber + "/" + service;
    try {
    OracleDataSource ods = new OracleDataSource();
    ods.setURL(url);
    Connection conn = ods.getConnection();
    // Create Oracle DatabaseMetaData object
    DatabaseMetaData meta = conn.getMetaData();
    // gets driver information
    out.println("<TABLE>");
    out.println("<TR><TD>");
    out.println("<B>JDBC Driver version</B>");
    out.println("</TD>");
    out.println("<TD>");
    out.println(meta.getDriverVersion());
    out.println("</TD>");
    out.println("</TR>");
    out.println("<TR><TD>");
    out.println("<B>JDBC Driver Name</B>");
    out.println("</TD>");
    out.println("<TD>");
    out.println(meta.getDriverName());
    out.println("</TD>");
    out.println("</TR>");
    out.println("<TR><TD>");
    out.println("<B>JDBC URL</B>");
    out.println("</TD>");
    out.println("<TD>");
    out.println(meta.getURL());
    out.println("</TD>");
    out.println("<TABLE>");
    conn.close();
    } catch (Exception e) {e.printStackTrace(); }
    %>
    <%-- end else if --%>
    <% } %>
    </BODY>
    </HTML>

  • How to Call  a Class method in another class.

    Hi All,
    I have created two class
    The class JavaAgent create a object of another TestFrame1 class . I am trying to call
    out.setSize(200,100);
    out.setVisible( true );
    above two method.
    I am a doing some thing wrong. I am getting the error " symbol cannot be resolved".
    public class JavaAgent extends AgentBase {
    private TestFrame1 out;
    private Session session;
    private Database db;
    private Frame frame;
         public void NotesMain() {
              try {
                   Session session = getSession();
                   AgentContext agentContext = session.getAgentContext();
    Database db = agentContext.getCurrentDatabase();
    String title = db.getTitle();
    // System.out.println ("Current database is \"" + title + "\"");
                   TestFrame1 out = new TestFrame1( );
    out.setSize(200,100);
    out.setVisible( true );
    Thread.sleep(250);
              } catch(Exception e) {
                   e.printStackTrace();
    import lotus.domino.*;
    import java.awt.*;
    import javax.swing.*;
    class TestFrame1
    private Session session;
    private Database db;
    TestFrame1( )// Constructor
    JFrame frame = new JFrame("Test Frame 1");
    }

    Hi,
    I guess you are not able to invoke setSize and setVisible method. Am i right ??
    First make sure your TestFrame class is compiled.
    The setSize() and SetVisible are defined in Component and inherited by JFrame.
    In order to use these methods you have to make your TestFrame as subclass of JFrame or provide a utility method
    and from there explicitly call these methods by using the associated JFrame reference.
    And in your JavaAgent class why you declared TestFrame1 twice?? it's really hard to predict your intention.
    Anyway i hope this code will helps you bit...
    import javax.swing.JFrame;
    public class JavaAgent{
         JavaAgent()
          * @param args
         public static void main(String[] args) {          
              TestFrame1 test = new TestFrame1("Test Frame1");
              test.setSize(250,250);
              test.setVisible(true);
    class TestFrame1 extends JFrame
         TestFrame1(String title)
              super(title);

  • Calling a class method from another class

    how can i call a method / function of one class without extending that class in another class.
    and one thing more i want want o check wether any Swing gui is open or closed.

    how can i call a method / function of one class without extending that class in another class.What?... Umm... You just call it... as in Foo.bar("doe ray me");
    i want want to check if any Swing gui is open or closed.Ummm, what? I don't understand the question. Do you mean find out if a particular java programming is allready running, of do you mean is the JPanel visible, or something else?

  • Calling public class method  from the servlet dopost() implementation

    Hi!
    My application is a simple application where i wrote a JSP page to enter the USERNAME and PASSWORD. And this JSP will call a HttpServlet
    with in which i am calling another Java class ValidateUser which will check aginst the Oracle Database table whether that Username and password combination exists and returns the user's name.
    But when i am trying to call that method is throwing me an error. here is the typical code i wrote.
    servlet
    package isispack;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.io.*;
    public class Login extends HttpServlet{
    public void doPost(HttpServletRequest req, HttpServletResponse res)
                   throws ServletException,IOException{
    String userId = req.getParameter("user_id");
    String password = req.getParameter("user_pass");
    // if uName is null .. user is not authorized.
    String uName = Validate(userId, password);
    and
    Validate class
    package isispack;
    import java.sql.*;
    import java.util.*;
    import java.lang.*;
    public class ValidateUser
    public String ValidateUser(String inputUserid, String inputPwd) throws
    SQLException{
         String returnString = null;
         String dbUserid = "isis"; // our Database user id
         String dbPassword = "isisos" ; // our Database password
         Connection con = DriverManager.getConnection("jdbc:odbc:JdbcOdbcDriver","isis","osiris");
         Statement stmt = con.createStatement();
         String sql= "select user_id from isis_table where user_id = '" inputUserid + "' and user_pass= '" + inputPwd +"' ;" ;
         ResultSet rs = stmt.executeQuery(sql);
         if (rs.next())
         returnString = rs.getString("user_id");
         stmt.close();
         con.close();
         return returnString ;
    The ERROR
    Error(18,18): method ValidateUser(java.lang.String, java.lang.String) not found in class isispack.Login
    One more thing i forgot to tell you. I am trying to run this application on JDeveloper. Please helpme out if you can . Thank you.
    -Sreekanth

    OK! I made it static method
    and tried to call the method as follows
    String uName = ValidateUser.ValidateUser(userId, password);
    even if i create the instence and
    ValidateUser Validate;
    then call
    String uName= Validate.ValidateUser(userId,password)
    In either case is giving me the following error.Tarun, am new to Java programming, please help me out. And can you please tell me where can i find things in consise to brush up my fundamentals?.
    Error(18,43): unreported exception: java.sql.SQLException; must be caught or declared to be thrown

  • Can you call a class method as an RFC function

    Hi
    I would like to know whether it is possible to instantiate a class in another system via RFC and then call a method eg. cl_abap_typedescr=>describe_by_name, of that class in the other system like you can with an RFC enabled function.
    Thanks
    Faaiez

    Its not possible to call a method like RFC.
    What you could do is write a RFC and within that instantiate the class and call desired method .
    And now you can call this RFC from the other system.
    Regards
    Raja

  • Can we call super class method from Overwrite method using SUPER keyword

    Hi All,
    For one of our requirement , I need to overwrite "Process Event" method of a feeder class  ,where process event is present is protected method. so when we are making a call , then its saying
    "Method  "process event"  is unknown or Protected  or PRIVATE ".
        But we are just copied the source code in the "Process Event" method to the Overwrite method.
    Can anyone provide me the clarification , why system behaving like this.
    Thanks
    Channa

    Hi,
    I think you can not.
    Because, only public attributes can be inherited and they will remain public in the subclass.
    for further detail check,
    http://help.sap.com/saphelp_nw70/helpdata/en/1d/df5f57127111d3b9390000e8353423/content.htm
    regards,
    Anirban

Maybe you are looking for

  • Is it possible to move content between private and public sites after publishing the latter?

    Hi. Is anyone else in this position? My institution kept its original iTunes U site after migrating our public content to the new public site last year. We now have separate public and private (university log-in only) sites and must maintain both. Th

  • Is there an easy way to switch iPhone microphone input from headphones to Bluetooth and back?

    When driving I plug my iPhone into the car stereo AUX jack with a cable to listen to music. To receive or make phone calls, or to use Siri, I use a Bluetooth (Jawbone) headset. If I'm playing music out the headphone jack and then answer a call, when

  • Publishing on the Net

    I am writing a book about my family, using InDesign CS5. The book has many chapters (of the order of 100), and each chapter has many photographs (it is like a photo album with some text). The average size of the best quality .pdf from each chapter is

  • Repeating sound effect problem

    I am looking to get a record scratch sound to play throughout my entire song. I have a MIDI ambient record scratch. What is the easiest way to get it to play in the whole song.

  • Can't see USB printer option in Cisco Connect

    Just fired up an e4200 router and was realy easy and everything working great HOWEVER I can a Canon MP490 printer that I have connected to the router via USB and Cisco Connect is only showing Wireless Printers as a connection option!! I am on a MAC u