Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
参数为两个类的Java函数_Java_Function_Class_Object - Fatal编程技术网

参数为两个类的Java函数

参数为两个类的Java函数,java,function,class,object,Java,Function,Class,Object,我需要做以下事情: class A int length, width, height; class B int length, width, density; (重要的是这些类具有不同的参数) 这是模式,不是代码。现在我想做一个函数,它可以做这样的事情: function compare(class first, class second) { if( first.length > second.length ) { ... } else { ...

我需要做以下事情:

class A
int length, width, height;

class B
int length, width, density;
(重要的是这些类具有不同的参数)

这是模式,不是代码。现在我想做一个函数,它可以做这样的事情:

function compare(class first, class second)
{
    if( first.length > second.length )
    { ... }
    else
    { ... }
}
并调用该函数:
比较(A,B)


有没有可能按照我描述的那样做,或者存在更好的方法?

创建一个类hirachy。定义一个包含长度和宽度的超类;让它实现可比性,并在超级类中只进行长度和宽度的比较;然后使用子类获得A和B类,这样默认情况下就不会比较宽度/高度。

首先,定义一个超类
A

public class A {
    private int length;

    public A(int length) {
       this.length = length'
    }

    public int getLength() { return length; }
}
并创建两个类,将其子类化,
B
C

public class B extends A { 
    public B(int length) {
       super(length);
    }
}

public class C extends A { 
    public B(int length) {
       super(length);
    }
}
现在您可以创建一个名为:

public void compare(A first, A second) {
    if(first.getLength() > second.getLength()) {
         // Do something..
    }
}
这可以称为:

A b = new B(5);

A c = new C(6);

compare(b, c);

完全有可能做到。当您使用对成员变量的直接访问时,您需要将它们公开。首先是类,这是错误的。先放一个。为什么继承是必要的?为什么有一个C类?我想你可以有一个接口
C
,但是考虑到用户想要访问一个公共属性,我把它移到一个超类是有意义的。