Originally posted by giri babu:
//first source file
package test;
public class Parent1{
protected int x=10;
public static void main(String args[]){
}
}
//*****************************
//second sourcefile
package best;
import test.Parent1;
public class child extends Parent1{
public void sub(){
System.out.println("in sub"+x);
}
public static void main(String args[]){
child ch=new child();
ch.x=1;
Parent1 p=new Parent1();//creating parent class object
System.out.println("child object ch:="+ch.x);
System.out.println("child object ch1:="+p.x); //This line giving me the error
ch.sub();
}
}
I hope this code will help you to explore the problem.
Actually u r accsssing the protected data member of a class that is in diffrent package if it is in same package than u may accsses it.Acssess specifier is protected sop it will be local to that package only. Make it public than accsses by following code
package test;
public class Parent1{
public int x=10;
public static void main(String args[]){
}
}
import test.Parent1;
public class child extends Parent1{
public void sub(){
System.out.println("in sub"+x);
}
public static void main(String args[]){
child ch=new child();
ch.x=1;
Parent1 p=new Parent1();
System.out.println("child object ch:="+ch.x);
System.out.println("child object ch1:="+p.x);
ch.sub();
}
}