Click here to Skip to main content
15,888,277 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
> 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 ...

Java
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;
	}
}
Posted

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.
 
Share this answer
 
Comments
petunia74 9-Feb-14 12:44pm    
Can you explain more please??
Java
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???
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900