日期:2014-05-20  浏览次数:20783 次

关于子父类继承之后成员变量的问题
class Fu
{
int x=100;
void f()
{
System.out.println(x*x);
}
}
class Zi_1 extends Fu
{
int x=2;
}
class Zi_2 extends Fu
{
int x=8;
}
class Demo
{
public static void main(String[] args)
{
Zi_1 z1=new Zi_1();
z1.f();
Zi_2 z2=new Zi_2();
z2.f();
}
}

我想的是用子类继承了父类里的f()方法 然后用子类里自己的x的值进行运算 但是最好不要重写父类的方法 ,因为子类既然继承了父类的,所以应该子类本身也有了f()方法的,该如何实现呢??我知道这种情况很少见,但我还是想知道该如何实现。。。

------解决方案--------------------
public class F {
int x =1;
void print(){
System.out.println(x );
}

public F(int x) {
this.x = x;
}
}

//



public class Z extends F{

public Z(int x) {
super(x);
}

int y;

}

//

import static org.junit.Assert.*;

import org.junit.Test;


public class ZTest {

@Test
public void test() {
Z z = new Z(0);
z.print();
}

------解决方案--------------------
public Zi_1(){
super.x = this.x;
}
------解决方案--------------------
1楼、2楼的方法都能实现,顶。我认为2楼的更适合:
class Zi_1 extends Fu {
int x = 2;
Zi_1(){
super.x=this.x;
}
}

class Zi_2 extends Fu {
int x = 8;
Zi_2(){
super.x=this.x;
}
}

class Demo {
public static void main(String[] args) {
Zi_1 z1 = new Zi_1();
z1.f();
Zi_2 z2 = new Zi_2();
z2.f();
}
}

------解决方案--------------------
不能通过?你确定你没开玩笑?
Java code

public class Test {
    public static void main(String[] args) {
        Zi_1 z1=new Zi_1();
        z1.f();
        Zi_2 z2=new Zi_2();
        z2.f();
    }
}

class Fu {
    int x = 100;
    void f() {
        System.out.println(this.x * this.x);
    }
}

class Zi_1 extends Fu {
    public Zi_1(){
        super.x = this.x;
    }
    int x = 2;
}

class Zi_2 extends Fu {
    public Zi_2(){
        super.x = this.x;
    }
    int x = 8;
}
//运行结果
//4
//64