Do objects inherit? - java

I have three classes A,B and C.
I have created object of class A in class B and I have inherit class B to class C.
Do the object of class A also inherit to class C?
Can I access member functions of class A through class C?

You have used composition between A and B (B encloses an instance of A) and inheritance between B and C. So from C you can "get at" methods in B by using the super keyword. You may (depending on scope) thus also access members of A from within C, but you are not doing it directly by inheritance, as would be the case if C inherits from B and B inherits from A.

Here is a small example for your case use it,
class A
{
String varOfA="Class A";
private String locOfA="Local variable";
}
class B extends A
{
int number=20;
}
class C extends B
{
int total=number;
void show()
{
System.out.println(super.varOfA);
//System.out.println(super.locOfA); //This is a private variable variable, so it
//won't be accessed from sub class
System.out.println(total);
}
}
public class MLInhert
{
public static void main(String args[])
{
C obj=new C();
obj.show();
}
}
Please let me know if i made any mistake in this answer. Because i'm a beginner here.

Depending on the access specifiers of the variables in the class it is decided which class level variable can be accessed. See the table below:
For more info refer : http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Related

access protected member in java by calling it from an object [duplicate]

I have a class called A in package1 and another class called C in package2. Class C extends class A.
A has an instance variable which is declared like this:
protected int protectedInt = 1;
Here is the code for class A
package package1;
public class A {
public int publicInt = 1;
private int privateInt = 1;
int defaultInt = 1;
protected int protectedInt = 1;
}
And here is the code for class C:
package package2;
import package1.A;
public class C extends A{
public void go(){
//remember the import statement
A a = new A();
System.out.println(a.publicInt);
System.out.println(a.protectedInt);
}
}
Eclipse underlines the last line in C.go() and says "A.protectedInt" is not visible. It seems that this conflicts with the definition of the "protected" keyword, given the Oracle documentation says:
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
What's going on here?
What's going on here?
You've misunderstood the meaning of protected. You can access the protected members declared in A from within C, but only for instances of C or subclasses of C. See section 6.6.2 of the JLS for details of protected access. In particular:
Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.
In addition, if Id denotes an instance field or instance method, then:
[...]
If the access is by a field access expression E.Id, where E is a Primary expression, or by a method invocation expression E.Id(. . .), where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S.
(Emphasis mine.)
So this code would be fine:
C c = new C();
System.out.println(c.publicInt);
System.out.println(c.protectedInt);
Since C is inheriting A, C can directly use the protected variable of A like below
public class C extends A{
public void go(){
System.out.println(protectedInt);
}
}
As per your code, you are creating an instance of A and accessing protected variable through that instance, which violates java's rule - A protected variable is not visible outside the package
Protected means:
a) This member will be accessible to all classes in the same package through A object’s reference.
b) For different packages, this will be accessible only inside subclasses of A, say B, and the reference used can be a B instance or of any subclass of B.
Let's take an example:
Let A be a parent class in some package, say com.ex1.
Let B and C be classes in different packages w.r.t to A, say com.ex2. Also, B extends A and C extends B.
We will see how we can use protected fields of A inside B (a subclass of A).
A's code:
public class A {
protected int a = 10;
}
B's code:
public class B extends A {
public void printUsingInheritance() {
// Using this
System.out.println(this.a);
}
public void printUsingInstantiation() {
// Using instance of B
B b = new B();
System.out.println(b.a);
// Using instance of C as C is a subclass of B
C c = new C();
System.out.println(c.a);
A a = new A();
System.out.println(a.a); // Compilation error as A is not a subclass of B
}
}
C's code:
public class C extends B {
}
For protected static:
Same rules apply except that in b) now it is accessible in any subclass of A by A's class reference. Reference
public void go(){
//remember the import statement
A a = new A();
System.out.println(a.publicInt);
System.out.println(a.protectedInt);
}
When you are doing A a = new A(); and a.protectedInt you trying to access protected member of A which is illegal according to java standards
Instead you can do this.protectedInt directly.
No need to instantiate Protection class inside Protection2 Class. You can directly call the protected variable without instantiating the Protection class. Because Protection2 class extends Protection class. So variable automatically inherited by subclass.
Try with below code:
public class Protection2 extends Protection{
Protection2()
{System.out.println("n_pro = " +n_pro);
}}
Within the same package where the protected member is declared, access is permitted:
package package1;
public class C extends A{
public void go(){
A a = new A();
System.out.println(a.protectedInt); // got printed
C c = new C();
System.out.println(c.protectedInt); // got printed as well
}
}
Outside the package where the protected member is declared, access is permitted if and only if by code that is responsible for the implementation of that object. In this case, C is responsible for the implementation of that object, so it could access the protected.
package package2;
public class C extends A{
public void go(){
A a = new A();
System.out.println(a.protectedInt); // compiler complains
C c = new C();
System.out.println(c.protectedInt); // got printed
}
}

Writing and accessin child class variable and function except those being inherited from parent class

I am trying to implement and access a new data members and a new member function in concrete class other than the one inherited from parent class. But can not do that.
Real Question is as follows:
Create an abstract class A with 2 data members and 2 member functions.
Create two concrete classes of the A class, named as B and C. Each concrete class should have 2 new data members and 2 new member functions. The data members and member functions in the 2 classes should not be the same. Write main() methods that create objects of each subclass, and send them enough messages to show the methods work.
Please help.
The code is --
import java.util.*;
abstract class A
{
abstract void display();
abstract void rules();
int players;
int length;
}
class B extends A
{
B(int a,int b)
{
players=a;
length=b;
}
void rules()
{
System.out.println("B rules");
}
void display()
{
System.out.println("In B players=" +players);
}
}
class C extends A
{
C(int a,int b)
{
players = a;
length = b;
}
void summary()// PROBLEM IS HERE . CAN NOT ACCESS summary
{
System.out.println("rules");
}
void display()
{
System.out.println("In C players=" +players + " length=" +length);
}
}
public class BatandBall
{
public static void main(String args[])
{
System.out.println("Airtel Champions League");
A obj = new B(10,3);
obj.display();
A obj1 = new C(11,8);
obj1.display();
obj1.summary(); // PROBLEM IS HERE . CAN NOT ACCESS summary
}
}
You cannot access it because the variable you created is of type A, not C. I know that actually obj1 is C but polymorphism makes it not C. As you can see, you are declaring an A here:
A obj1;
No matter what values you put in obj1, it is still of type A. So how do you call summary? You need a cast! This will change obj1's type to C:
(C)obj1
And then you can just use this to call summary:
((C)obj1).summary();
That's easy isn't it?
And by the way, your C class doesn't implement rules as defined in A. You should probably implement that or your code won't compile.

Java: Implementing an interfacing by inheriting a class

Time-appropriate greetings :)
Working in Java, I have an Interface A. All implementors of this Interface also extend class B, but B does not implement A. In a class where we use an instance of A (referenced as A), it is cast to a B Reference so that we can use a Method defined in class B. It makes sense conceptually that the Method should belong in Interface A too.
Can you think of a reason not to introduce the Method to Interface A, so that we don't have to cast it to B? Should I maybe override the Method in the subclasses and just call the super version, so that it's easier to navigate in the IDE etc?
In a class where we use an instance of A (referenced as A), it is cast to a B Reference so that we can use a Method defined in class B.
So I'm assuming you have this scenario
public void doStuff(A aType){
...
B bType = (B) aType;
...
}
If this is true, can this work?
private <T extends B & A> void example(T type){
type.aStuff();
type.doBStuff();
}
I created the following to test this.
public class Foo{
private static interface A{
void aStuff();
}
private static class B{
public void doBStuff(){
System.out.println("B stuff");
}
}
private static class AB extends B implements A{
public void aStuff(){
System.out.println("A stuff");
}
}
public static void main(String[] args) {
Foo foo = new Foo();
foo.example(new AB());
}
// method "example" already given
}
Gave me
A stuff
B stuff
Why not creating an abstract class which extends B and implements A? Assuming this class would be called C, your other classes would extend C and implement the method required by A, but will provide you with the methods available in B without casting.
I think that moving methods now would not be a good idea, maybe, at most, have B implement A (assuming you have no other classes which you haven't talked about which are dependent on the classes and interfaces you mentioned).

Descendant not seeing clone() due to access privilige violation? [duplicate]

I have a class called A in package1 and another class called C in package2. Class C extends class A.
A has an instance variable which is declared like this:
protected int protectedInt = 1;
Here is the code for class A
package package1;
public class A {
public int publicInt = 1;
private int privateInt = 1;
int defaultInt = 1;
protected int protectedInt = 1;
}
And here is the code for class C:
package package2;
import package1.A;
public class C extends A{
public void go(){
//remember the import statement
A a = new A();
System.out.println(a.publicInt);
System.out.println(a.protectedInt);
}
}
Eclipse underlines the last line in C.go() and says "A.protectedInt" is not visible. It seems that this conflicts with the definition of the "protected" keyword, given the Oracle documentation says:
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
What's going on here?
What's going on here?
You've misunderstood the meaning of protected. You can access the protected members declared in A from within C, but only for instances of C or subclasses of C. See section 6.6.2 of the JLS for details of protected access. In particular:
Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.
In addition, if Id denotes an instance field or instance method, then:
[...]
If the access is by a field access expression E.Id, where E is a Primary expression, or by a method invocation expression E.Id(. . .), where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S.
(Emphasis mine.)
So this code would be fine:
C c = new C();
System.out.println(c.publicInt);
System.out.println(c.protectedInt);
Since C is inheriting A, C can directly use the protected variable of A like below
public class C extends A{
public void go(){
System.out.println(protectedInt);
}
}
As per your code, you are creating an instance of A and accessing protected variable through that instance, which violates java's rule - A protected variable is not visible outside the package
Protected means:
a) This member will be accessible to all classes in the same package through A object’s reference.
b) For different packages, this will be accessible only inside subclasses of A, say B, and the reference used can be a B instance or of any subclass of B.
Let's take an example:
Let A be a parent class in some package, say com.ex1.
Let B and C be classes in different packages w.r.t to A, say com.ex2. Also, B extends A and C extends B.
We will see how we can use protected fields of A inside B (a subclass of A).
A's code:
public class A {
protected int a = 10;
}
B's code:
public class B extends A {
public void printUsingInheritance() {
// Using this
System.out.println(this.a);
}
public void printUsingInstantiation() {
// Using instance of B
B b = new B();
System.out.println(b.a);
// Using instance of C as C is a subclass of B
C c = new C();
System.out.println(c.a);
A a = new A();
System.out.println(a.a); // Compilation error as A is not a subclass of B
}
}
C's code:
public class C extends B {
}
For protected static:
Same rules apply except that in b) now it is accessible in any subclass of A by A's class reference. Reference
public void go(){
//remember the import statement
A a = new A();
System.out.println(a.publicInt);
System.out.println(a.protectedInt);
}
When you are doing A a = new A(); and a.protectedInt you trying to access protected member of A which is illegal according to java standards
Instead you can do this.protectedInt directly.
No need to instantiate Protection class inside Protection2 Class. You can directly call the protected variable without instantiating the Protection class. Because Protection2 class extends Protection class. So variable automatically inherited by subclass.
Try with below code:
public class Protection2 extends Protection{
Protection2()
{System.out.println("n_pro = " +n_pro);
}}
Within the same package where the protected member is declared, access is permitted:
package package1;
public class C extends A{
public void go(){
A a = new A();
System.out.println(a.protectedInt); // got printed
C c = new C();
System.out.println(c.protectedInt); // got printed as well
}
}
Outside the package where the protected member is declared, access is permitted if and only if by code that is responsible for the implementation of that object. In this case, C is responsible for the implementation of that object, so it could access the protected.
package package2;
public class C extends A{
public void go(){
A a = new A();
System.out.println(a.protectedInt); // compiler complains
C c = new C();
System.out.println(c.protectedInt); // got printed
}
}

JAVA How to pass initialization information to multiple superclasses

I have another question on constructors. I have a hierarchy of more than 2 layers, Say
A,
B extends A,
C extends B.
Can I get constructors from all three layers to fire when I create an instance of C? What if I want to pass super(int anArgumentForA, int anArgumentForB); Is that even possible? Seems like that's where it's going but I don't find a way to differentiate the arguments going to A vs B. Default constructor from B seems to run and I can't feed it the value it needs in order to run a different constructor because I don't know how.
You can have each layer call super(...) to set the information in each layer.
public Class A
{
public A(Object a, Object b)
{
//do any initialization needed
}
}
public Class B extends A
{
public B(Object a, Object b, Object c)
{
super(a, b); //This will call A(a, b)
//do any initialization needed
}
}
public Class C extends B
{
public C(Object a, Object b, Object c)
{
super(a, b, c); //This will call B(a, b, c)
//do any initialization needed
}
}
Keep in mind I don't think it is advisable to use these constructors to set the Objects to a variable at each level. So you don't want to have the constructors for A, B, and C each set some object Object x = a in the constructor. Only one, at most, level in the hierarchy should maintain a reference to the Objects being passed into the constructors.
In the world of Java, when you are extending another class, you only see your direct super class' constructor. The super class is supposed to proper encapsulate the super-super class constructor.
That means, in your case, B should provide a constructor that proper encapsulate A. In case B cannot determine the argument to pass to A's constructor, it is reasonable to ask for it in B's own constructor:
class A {
A (int aArg) {
// init base on aArg
}
}
class B extends A {
B (int aArg, int bArg) {
super(aArg);
// extra initialization base on bArg and aArg
}
}
class C extends B {
C() {
super(SOME_A_ARG, SOME_B_ARG);
}
}
As per Java Specification the constructors are not inherited by sub-classes.
So, as per you requirement you should keep in mind that the super class should have scope to pass objects.
When you are declaring a class by extending another class B extends A and C extends B , you should define the constructor
such a way so that you can customize that for initialization . This declaration always depends on the depth and hierarchy of the
inheritance .
class A{
A(Object firstObj, Object secondObj){
//Do you stuff for initialization
}
}
class B extends A{
//Keep in mind that this B class will be inherited by other class
B(Object firstObj,Object secondObj,Object thirdObj){
//Call super class constructor
super(firstObj,secondObj);
//Do other initialization stuff here
}
}
class C extends B{
//Keep in mind that this C class will be inherited by other class
C(Object firstObj,Object secondObj,Object thirdObj){
//Call super class constructor
super(firstObj, secondObj, thirdObj); //call constructor of B
//Do other initialization stuff here
}
}
It always depends how you parent class constructor has defined. It depends on the number of parameter passes to parent class constructor, you need to call accordingly from child class constructor.
Hope it will help you.

Categories

Resources