【问题标题】:How to invoke a class in another package? [duplicate]如何调用另一个包中的类? [复制]
【发布时间】:2016-11-30 10:11:10
【问题描述】:

我在一个启动项目中,我在 Eclipse 中将它拆分为两个包,其中一个具有主要方法和另一个 .java 类,另一个具有另一个具有辅助方法的 .java 类。 我想知道如何调用辅助包中存在的方法以在主包中没有主方法的 .java 类中使用它。如何导入它以及如何访问该类中的方法?我是 java 新手,需要这个项目。

【问题讨论】:

  • 也许你只是指定包名?

标签: java class import


【解决方案1】:

如果我理解正确(如果您粘贴一些示例代码可能会更好)在 main 方法中编写您的代码,调用您需要的。 然后在顶部写上你需要的导入,或者在 Eclipse 中使用 CTRL+MAIUSC+O 来导入你需要的包。

【讨论】:

    【解决方案2】:

    您必须在课程的开头使用import,但如果您使用其自动导入快捷方式(应为Ctrl + Shift + O),Eclipse 会自动为您提供。

    类似这样的:

    班级User

    package model;
    
    public class User {
    
        private String name;
        private Integer age;
    
        public String getName() { return this.name; }
        public void setName(String name) { this.name = name; }
    
        public String getAge() { return this.name; }
        public void setAge(Integer age) { this.age = age; }
    
        @Override
        public void toString() {
            return "Name: " + this.name + "; Age: " + this.age;
        }
    }
    

    UserAttributes 类(您需要在其中导入其他类)

    package logic;
    
    import model.User; //this is the line you must include (or hit Ctrl+Shift+O in Eclipse)
    
    public class UserAttributes {
    
        public static void main(String[] args) {
            User john = new User("john", 30);
    
            System.out.println(john);
        }
    }
    

    Eclipse 可以成为一个很好的开发工具,如果您使用它的特性,它会让您的生活变得更加轻松。其中一些可以通过快捷方式直接访问。这是list of some very useful(在我看来)。

    希望对你有所帮助。

    【讨论】:

      【解决方案3】:

      是的,这是我的代码

      package ex_19;
      import ex_16_17.Date;
      import ex_18.HeartRates;
      
      public class HealthProfile {
          private String nome;
          private String sobrenome;
          private String sexo;
          private Date dataNascimento;
          private float altura;
          private float peso;
      
      .......
      
          HeartRates hr = new HeartRates(this.getNome(), this.getSobrenome(), this.dataNascimento.getDia(), this.dataNascimento.getMes(), this.dataNascimento.getAno());
      
          public int calcIdade(){
              return hr.calculaIdade();
          }
      
          public int freqMaxima(){
              return hr.feqMax();
          }
      
          public String freqAlvo(){
              return hr.feqAlvo();
          }
      

      我想知道如何使用这样的代码,在我的 main 上工作,当我调用 calcIdade() 时,语法是什么?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-12
        • 2013-04-20
        • 2019-11-15
        • 1970-01-01
        • 2021-09-07
        • 2014-10-27
        • 2011-08-06
        相关资源
        最近更新 更多