[英]Using Java Inheritance, how do I refer to a specific subclass while I'm in the superclass
I have 3 different Classes: 我有3种不同的课程:
Class 1 (Super Class) Class 2 (SubClass) Class 3 (SubClass) 1级(超级类)2级(子类)3级(子类)
In Class 1, I have an instance variable called NUMBER, and a method called myNumber. 在第1类中,我有一个名为NUMBER的实例变量和一个名为myNumber的方法。
I am trying to make an if/else statement, so that if we are calling the .myNumber method for Class 2, NUMBER equals 7. However, in Class 3, I want that number to equal 8. 我试图做一个if / else语句,以便如果我们为类2调用.myNumber方法,则NUMBER等于7。但是,在类3中,我希望该数字等于8。
My if else statement looked like this: 我的if else语句看起来像这样:
if (Class2)
{
myNumber = 7
}
else if (Class3)
{
myNumber = 8
}
However, I have no idea how to refer to Class2 and Class3, while I'm making the code in Class3. 但是,当我在Class3中编写代码时,我不知道如何引用Class2和Class3。
Any help would be great! 任何帮助将是巨大的! :)
:)
You don't understand polymorphysm. 您不了解多态性。 Instead of use
if/else
statements you need to extends from desired class and introduce new behavior with help of overriding methods. 无需使用
if/else
语句,您需要从所需的类扩展并在覆盖方法的帮助下引入新的行为。 All code that accept parent class will accept child classes because all of them is-a parent ( https://en.wikipedia.org/wiki/Is-a ), and can do anything what parent do, but may differ they behavior. 所有接受父类的代码都将接受子类,因为它们都是父类( https://en.wikipedia.org/wiki/Is-a ),并且可以执行父类的任何操作,但是可能会改变它们的行为。 Example:
例:
class ClassOne {
private int number = 1;
public int getNumber() {
return number;
}
}
class ClassTwo extends ClassOne {
public int getNumber() {
return 2;
}
class ClassThree extends ClassOne {
public int getNumber() {
return 3;
}
Test class: 测试类别:
public class TestClass {
public static void main(String... args) {
ClassOne classOne = new ClassOne();
ClassOne classTwo = new ClassTwo();
ClassOne classThree = new ClassThree();
TestClass test = new TestClass();
test.printNumberFrom(classOne); // prints 1
test.printNumberFrom(classTwo); // prints 2
test.printNumberFrom(classThree); // prints 3
}
//knows only about ClassOne but may accept it's childs
public void printNumberFrom(ClassOne classOne) {
System.out.println(classOne.getNumber());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.