• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

How does this work ?

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why does the following give compilation error at line 1.
Class B extends Class A which is in a different package.

//in file A.java
package p1;
public class A
{
protected int i = 10;
public int getI() { return i; }
}

//in file B.java
package p2;
import p1.*;
public class B extends p1.A
{
public void process(A a)
{
a.i = a.i*2; // line 1
}
public static void main(String[] args)
{
A a = new B();
B b = new B();
b.process(a);
System.out.println(a.getI());
}
}
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
when you are accessing the variable 'i', you are not making use of inheritance, hence the problem.The protected variable 'i' will not be visible to classes outside the pacakge unless you make use of inheritance.
So somethin like this will work-
package p1;
public class A
{
protected int i = 10;
public int getI() { return i; }
}

package p2;
import p1.*;
public class B extends p1.A
{
public void process()
{
i = i*2; // line 1
System.out.println(getI());
}
public static void main(String[] args)
{
new B().process();
}
}

Hope this helps!

Brijesh
 
Can you shoot lasers out of your eyes? Don't look at this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic