Win a copy of GANs in ActionE this week in the AI forum
or WebAssembly in Action in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Knute Snortum
Sheriffs:
  • Liutauras Vilda
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Joe Ess
  • salvin francis
  • fred rosenberger

jq+ Question ID :957672686580

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Consider following two classes:
//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;
}
public static void main(String[] args)
{
A a = new B();
B b = new B();
b.process(a);
System.out.println( a.getI() );
}
}
What will be the output of compiling and running class B ?
Explanation is given:
--------------------
Although, class B extends class A and 'i' is a protected member of A, B still cannot access i.....why ?
Pls..explain the same.
THANKS IN ADVANCE.
Ratul Banerjee
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ratul,
Protected members can only be accessed in the subclasses of different packages using the instance of super class. You can not access i using a.i . But you can access the same by new a().i;
Regards,
Pasu Jags.
 
Ranch Hand
Posts: 290
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1)same package subclass protected memeber's of the superclass accessible through the superclass reference variable.
2)subclass different package, access to protected memeber's of the superclass through the superclass reference varaible not allowed.
 
ratul banji
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Pasu and Nitin.
I think .. i got it.
 
That's a very big dog. I think I want to go home now and hug this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!