一类具有相同名称JAVA的静态和非静态方法 [英] Static and non-static method in one class with the same name JAVA

查看:46
本文介绍了一类具有相同名称JAVA的静态和非静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道不可能在一个类中重写一个方法.但是有没有办法使用非静态方法作为静态方法呢?例如,我有一个加数字的方法.我希望此方法在没有对象的情况下有用.是否可以在不创建其他方法的情况下做类似的事情?

I know it is impossible to override a method in one class. But is there a way to use a non-static method as static? For example I have a method which is adding numbers. I want this method to be usefull with an object and also without it. Is it possible to do something like that without creating another method?

我的意思是,如果我将一个方法设为静态,我将需要它接受参数,并且如果我创建了一个已经设置了变量的对象,那么再次在具有相同参数的对象上调用函数将非常不舒服.

What I mean is, if I make a method static I will need it to take arguments, and if I create an object with variables already set it will be very uncomfortable to call function on my object with same arguments again.

public class Test {

    private int a;
    private int b;
    private int c;

    public Test(int a,int b,int c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public static String count(int a1,int b1, int c1)
    {        
        String solution;
        solution = Integer.toString(a1+b1+c1);
        return solution;
    }


    public static void main(String[] args) {

       System.out.println(Test.count(1,2,3));
       Test t1 = new Test(1,2,3);
       t1.count();
    }

}

我知道代码不正确,但是我想展示自己想做的事.

I know the code is incorrect but i wanted to show what I want to do.

推荐答案

我希望此方法在有对象的情况下也有用,在没有对象的情况下也是如此.是否有可能做类似的事情而不创建另一个方法?

I want this method to be usefull with an object and also without it. Is it possible to do something like that without creating another method?

您将不得不创建另一个方法,但是您可以使非静态方法调用静态方法,这样您就不会重复代码,并且如果您将来想更改逻辑,则只需执行此操作即可.在一个地方.

You will have to create another method, but you can make the non-static method call the static method, so that you do not duplicate the code and if you want to change the logic in the future you only need to do it in one place.

public class Test {
    private int a;
    private int b;
    private int c;

    public Test(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public String count() {
        return count(a, b, c);
    }

    public static String count(int a1, int b1, int c1) {
        String solution;
        solution = Integer.toString(a1 + b1 + c1);
        return solution;
    }

    public static void main(String[] args) {
        System.out.println(Test.count(1, 2, 3));
        Test t1 = new Test(1, 2, 3);
        System.out.println(t1.count());
    }
}

这篇关于一类具有相同名称JAVA的静态和非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆