Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

access problems

 
Amartya Datta Gupta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.. I am an absolute beginner in java.... and I have run in2 a problem....
I have 2 classes c1 and c2.
c1 has.. protected x, protectected c1(), protected void sho();
c2 extends c1..

now c2 has a the main fn...... now i create an object of type c1 inside main;
it works fine as long as c1 and c2 are in same package..... as soon i put them in different packages, they stop working... compiler says... cant access c1() protected access......... i dont understand why...

code.............................................

package p2;
public class c2 extends p1.c1
{
protected int y;

protected c2(int x,int y)
{
super(x);
this.y=y;
}

protected void sho()
{
super.sho();
System.out.println(y);
}

public static void main(String args[])
{
c2 ob=new c2(10,20);
ob.sho();

p1.c1 ob1=new p1.c1(100);
ob1.sho();

//sho();
}
}
-------------------------------------------------------

package p1;

class c1
{
protected int x;

protected c1(int x)
{
this.x=x;
}

protected void sho()
{
System.out.println(x);
}
}
-------------------------

p1/c2.java:25: c1(int) has protected access in p1.c1
p1.c1 ob1=new p1.c1(100);
^
p1/c2.java:26: sho() has protected access in p1.c1
ob1.sho();
^
2 errors
 
Pratik D mehta
Ranch Hand
Posts: 121
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all please use code tag for writing code.

You are getting a error because protected variables of a parent class and child class in different packages can be accessed only from the instance of the child class and not parent class.

This is only if the parent and the child class are in different packages.

In your case protected variable of class c1 can only be accessed by instance of class c2 and not c1.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, please UseRealWords (not text message abbreviations like "in2"). Thanks! (And try to restrict yourself to a single period "." unless using them as ellipses ("..."))
 
Amartya Datta Gupta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
Amartya Datta Gupta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David Newton wrote:Also, please UseRealWords (not text message abbreviations like "in2"). Thanks! (And try to restrict yourself to a single period "." unless using them as ellipses ("..."))


I will remember that from now on!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic