访问父类变量的父类? [英] access to a parent class of parent class variable?

查看:81
本文介绍了访问父类变量的父类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>嗨。

我正在做java数据结构书的练习c-2.5。但我有一个问题。

问题:编写一个由三个类组成的程序,A,B,C,这样B扩展A和C扩展B.每个类应该定义一个名为的实例变量 X。描述一种方法,用于在C中访问并将A的x版本设置为给定值,而不更改B或C的版本。

我写了这三个类但是在方法setX()中有错误。请引导我...



<前一个=java> 公共 class A {

public int x;
public A(){
x = 0;
}
}


public class B extends A {

private int x;
public B()
{
x = 0;

}
}


public class C extends B {

public int x;
public C(){
x = 0;
}
public void setX( int a){

super .x = a;
}
}

解决方案

看起来这样的练习很受欢迎,这些天......
您收到错误,因为您的代码正在尝试访问B类的私有成员,这在文明编程语言中当然是非法的。

提示:您可以声明公开的方法来更改对象状态。


  public   class  C  extends  B {

public int x;
public C(){
x = 0;
}
public void setX( int a){

A d = new A();
d.x = a;

}
}





是真的???

> hi.
I am doing exercise c-2.5 of java data structure book. but I have a problem.
question : write a program that consist of three classes, A, B, C, such that B extends A and C extends B. Each class should define an instance variable named "x". Describe a way for a method in C to access and set A's version of x to a given value, without changing B or C's version.
I wrote these three classes but in method setX() there is errors.please guide me ...

public class A {

	public int x;
	public A(){
		x=0;
	}
}


public class B extends A{

	private int x;
	public B()
	{
		x=0;
		
	}
}


public class C extends B{

	public int x;
	public C(){
		x=0;
	}
	public void setX(int a){
	
		super.x=a;
	}
}

解决方案

It looks such exercise is quite popular, these days...
You get an error because your code is trying to access a private member of class B, and that's of course illegal in civilized programming languages.
Hint: you can declare public methods for changing state of objects.


public class C extends B{

	public int x;
	public C(){
		x=0;
	}
	public void setX(int a){
	
		A d=new A();
		d.x=a;
		
	}
}



is it true???


这篇关于访问父类变量的父类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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