gpt4 book ai didi

具有接口(interface)成员变量和成员方法的 Java 类的行为不同。请解释

转载 作者:行者123 更新时间:2023-12-01 18:16:02 25 4
gpt4 key购买 nike

接口(interface)和类Number1,后来的Number2,等等。当我尝试在方法 add() 中使用成员数据时,它要求我首先将其转换为类类型。但是,如果我在方法 add() 中使用成员方法,它并不要求我强制转换为类类型。任何解释将不胜感激。

下面附有代码。

<小时/>
    package mynums;
//Interface for all my number types, Number1, Number2 (not shown), etc
public interface NumberIF
{

public int getNum();

public void setNum(int numx);

//I will have other types of numbers not just Number1.
//I will have Number2, etc.
public void add(NumberIF f1, NumberIF f2);
public void print();
}


package mynums;
//There will be other types of numbers Number2, Number3
//all doing these operations but different.
//This is just to test the concept.
//But I have a problem here.
public class Number1 implements NumberIF
{
private int num;

public Number1()
{
num = 1;
}

public Number1(int numx)
{
num = numx;
}

public int getNum()
{
return (num);
}

public void setNum(int numx)
{
num = numx;
}

public void add(NumberIF f1, NumberIF f2)
{
int numt;

/**
* Why to use member variables I must specify the type of class.
* Why to use member method I do not have to specify type of class.
*/

//numt = f1.num + f2.num; ERROR

// either one works
//Why accessing member data is different from accessing member method.
numt = ((Number1)f1).num + ((Number1)f2).num;
numt = f1.getNum() + f2.getNum();

num = numt;

}

public void print()
{
System.out.println(num);
}

static public void main(String[] args)
{
Number1 f1, f2, f3;

f1 = new Number1(1);
f2 = new Number1(2);
f3 = new Number1(0);

f3.add(f1, f2); // 1 + 2= 3
f3.print();
}
}

最佳答案

Java 是一种静态类型语言。

静态类型NumberIF的变量不一定指向Number1类型的对象,因此这些对象可能没有字段num

您只能使用变量的静态类型(及其父类(super class)型)的成员。

关于具有接口(interface)成员变量和成员方法的 Java 类的行为不同。请解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60366339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com