简体   繁体   English

Java-已声明方法但无法引用它

[英]Java - Method declared but cannot reference it

I am kind of new to Java, although I've programmed in other procedural langauages for 25 years. 尽管我已经在其他过程语言中编程了25年,但我还是Java的新手。 So, I'm trying to teach myself Java. 因此,我正在尝试自学Java。 Trying to write some silly program consisting of two files: a Class called "Customer", and a main program called "Silly4". 试图编写一个包含两个文件的愚蠢程序:一个名为“ Customer”的类和一个名为“ Silly4”的主程序。

I'm pretending to implement a credit card system for a bank type company (even though the majority of my experience was in defense contracting). 我假装为一家银行类型的公司实施信用卡系统(即使我的大部分经验是在国防承包方面)。 I figure this would be a good teaching example for me. 我认为这对我来说将是一个很好的教学示例。

Trying to build a credit card data structure called "Customer" such that (for the time being) it can accomodate 1000 customers. 试图建立一个称为“客户”的信用卡数据结构,以便(暂时)它可以容纳1000个客户。 In the main program "Silly4", I instantiate this Customer class as "cust2", and then from there I attempt to work with "cust2". 在主程序“ Silly4”中,我将此客户类实例化为“ cust2”,然后从那里尝试使用“ cust2”。 I try to retrieve customer number 5's (j=5) credit card balance. 我尝试检索客户编号5的(j = 5)信用卡余额。 So far, so good. 到现在为止还挺好。

Then from there I attempt to declare in the class Customer another method (for future use) which I arbitrarily call "bal44", and then I attempt to reference it in the main program Silly4 as " ball44(5541);". 然后从那里尝试在类Customer中声明另一个方法(供将来使用),我随意调用“ bal44”,然后尝试在主程序Silly4中将其引用为“ ball44(5541);”。

So I compile class Customer, then compile program Silly4, and I'm getting a compile error "java:52: error: cannot find symbol" for the reference to method "bal44(5541)" in main program "Silly4". 因此,我编译了类Customer,然后编译了程序Silly4,并且在主程序“ Silly4”中收到对方法“ bal44(5541)”的引用的编译错误“ java:52:错误:找不到符号”。 I'm confused. 我糊涂了。 I've declared and successfully compiled the class Customer with "bal44" in there, but Java is telling me it can't find it. 我已经声明并成功编译了其中带有“ bal44”的Customer类,但是Java告诉我找不到它。 I'm confused. 我糊涂了。

Please excuse all the extraneous println's, I use them to see how the program is moving along. 请原谅所有多余的println,我用它们来查看程序的运行情况。

Here is class Customer: 这是类客户:

// Data Structure for credit card database

public class Customer {
    private String name;
    private int accountNo;
    private double balance;
    private boolean Overdue;

    // Getters, setters, constructor...


    public void setName( String new_name )
        {  name = new_name;  }


    public void setAccount( int new_account )
        {  accountNo = new_account;  }


    public void setBalance( double new_bal )
        {  System.out.println( " Start proc setBalance ");
           balance = new_bal;
           System.out.println( " Finish proc setBalance ");
            }

    public double getBalance()
        {  System.out.println( " Start proc getBalance ");
           System.out.println( " proc getBalance , balance= " + balance + " end print");
           return balance;
           // how to specify which element of array[1000] ? balance I want ?
           // System.out.println( " Finish proc getBalance ");
            }

    // Add new customer to credit card system
    //   (note - index in array Customer[i] is worry of main program
    //
    public void addCustomer( String name2, int account2, double bal2 )
         { name      = name2;
           accountNo = account2;
           balance   = bal2;
             }

    public void bal44 ( int account3 )
         { accountNo = account3; }


    // Constructor

    Customer ()
        {   name      = "John Smith";
            accountNo = 1005;
            balance   = 125.43;
            Overdue   = false;    }

    // see page 1032 Liang for definition complex Object and get-Procs for it


}    

Here is main program/class Silly4: 这是主程序/类Silly4:

class Silly4 Silly4类

{ // Program for credit card database {//信用卡数据库程序

public static void main(String[] args)
 {
     double bal2, bal3;
     int i;                 // loop counter
     int j;

     bal2 = 151.47;
     bal3 = 5.0;           // just initialize

    // And then you can create an array of it:

    System.out.println("** Program Silly4 Running **"); 

    Customer[] cust2 = new Customer[1000];

    System.out.println("** Array cust2 instantiated **"); 

    for(i=0; i<=999; ++i)
    {
         cust2[i] = new Customer();
    }

    System.out.println("** Array2 cust2 Obj initialized **"); 



    //  try to code this eventually  -   cust2.balance = 151.47 ;
    //

    j = 5;                 // customer no. 5

    cust2[j].setBalance( bal2 );


    bal3 = cust2[j].getBalance() ;


    System.out.println("** Balance Customer " + j + " is " + bal3);

    // Add a new customer
    //  comment out -  addCustomer( "Steve Jones", 5541, 1.0 );

    bal44( 5541 );      // test out declaring new method "bal44"


    System.out.println("** End of Silly4  **");

    }

} }

When you call 你打电话时

 bal44( 5541 ); 

Without any object, Java assumes it as a "this" object and searches for that method in Silly4 not in Customer class. 如果没有任何对象,Java会将其视为“此”对象,并在Silly4中而不是在Customer类中搜索该方法。 Call that method from Silly4 like you are calling other method of customer class. 就像您正在调用客户类的其他方法一样,从Silly4调用该方法。 eg 例如

cust2[j]. bal44( 5541 ); or something like that.

Read more about "this" here https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html 在此处阅读有关“ this”的更多信息https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

PS A bonus point to note here is that static method's like main method do not have this reference available to them. PS在这里要注意的一个好处是,静态方法(如main方法)没有引用。 So, technically here it is searching for a class-level(static) method in Silly4 rather than instance method. 因此,从技术上讲,它是在Silly4中搜索类级(静态)方法,而不是实例方法。 :) :)

You basically answered yourself in the first sentence of your query. 您基本上是在查询的第一句话中回答了自己。 Java is not a purely procedural language, it's an object-oriented language. Java不是纯粹的过程语言,它是一种面向对象的语言。

That means that when you declare methods, they are not just scoped functions. 这意味着在声明方法时,它们不只是作用域函数。 A method declared in a class is not similar to a function declared in an include d file in C. It's something that can be only called from the scope of an object of the enclosing class . 在类中声明的方法与在C中的include d文件中声明的函数不同。只能在封闭类对象范围内调用该方法。 In other words, you don't have a function named bal44 . 换句话说,您没有名为bal44的函数。 You have a method bal44 of class Customer , which means that you need to ask an object fo class Customer to execute it for you, similar to how you call setBalance() . 您拥有类Customer方法 bal44 ,这意味着您需要让类Customer的对象为您执行该对象,类似于您如何调用setBalance()

EDIT: As another comment mentions, what might be confusing you more is that whenever you use a method name without qualifiers, Java treats it as a shortcut of asking this (the current object) to execute the method, so technically, method(args) is a shortcut for this.method(args) . 编辑:正如另一条评论所述,可能使您更困惑的是,每当您使用不带限定符的方法名称时,Java会将其视为要求this (当前对象)执行该方法的快捷方式,因此从技术上讲, method(args)this.method(args)的快捷方式。 Therefore, whenever you are within the scope of a single class, a class's methods will behave almost as traditional functions. 因此,只要您在单个类的范围之内,一个类的方法将几乎像传统函数一样工作。

See, here is the problem : You are using the bal44(5541) , but you made that method non static, meaning you need to make an object of your class (Customer) and then say for example Customer customer = new Customer() customer.bal(5541); 瞧,这是问题所在:您正在使用bal44(5541) ,但是使该方法成为非静态的,这意味着您需要创建您的类(客户)的对象,然后说例如Customer customer = new Customer() customer.bal(5541); If you want to call that method without making an object of its class, simply put the keyword "static" in the method's header. 如果要在不创建该类对象的情况下调用该方法,只需在该方法的标题中放入关键字“ static”。 public static void bal44(int num)

Further explanation : Since you are from a procedural language, recall the main difference is the usage of objects. 进一步说明:由于您来自过程语言,因此回想起来的主要区别是对象的用法。 An object is something that has several traits, or attributes, and actions or behaviors. 对象是具有多个特征或属性以及动作或行为的东西。 For example a car, its attributes are its color, speed, etc. and its main action/behavior is drive. 例如,一辆汽车,其属性是颜色,速度等,其主要动作/行为是驾驶。 Attributes are variables, and Behaviors/Actions are methods. 属性是变量,行为/动作是方法。 eg 例如

car.drive(); car.setColor("red");

I hope that helped? 希望对您有帮助吗? If you don't understand you can PM me or respond here and I'll explain in further detail 如果您不理解,可以给我PM,或者在这里回复,我会进一步详细解释

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么枚举引用变量不能单独声明在方法之外? - Why enum reference variables cannot be declared outside method on its own? 我可以在Java接口中声明的方法中使用实现类的引用吗 - Can i use reference of implementing class into method declared in Interface in java “找不到符号:方法”但方法是在 Storm.java 中定义和声明的 - "Cannot find symbol: Method" but method is defined and declared in Storm.java Java找不到符号get.Method,但声明了Method - Java Cannot find symbol get.Method but Method is declared 如果方法无法引发声明的已检查异常,则配置Java编译器是否出错 - Configure Java Compiler for Error if method cannot throw declared checked Exception 为什么实例方法的Java方法引用无法分配给Consumer接口 - Why Java Method Reference of instance method cannot be assigned to Consumer interface 检测是否在Java中的接口中声明了方法 - Detecting if a method is declared in an interface in Java 收到“无法对非静态方法进行静态引用”错误,但我尚未将要从中调用的方法声明为静态方法 - getting “cannot make a static reference to the non-static method” error, but I haven't declared the method I'm calling from as static “找不到符号:方法”但声明了方法 - “cannot find symbol: method” but the method is declared 无法静态引用非静态方法(Java) - Cannot make static reference to the non-static method (Java)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM