Home > front end >  Java accesing properties with same name in both classes
Java accesing properties with same name in both classes

Time:01-12

I have 2 classes, A and B which B inherits from A. Both classes have a property of type int called w.

In class A w is public and in class B w is private.

I made an object of type A using B constructor - A a = new B()

Yet when i tried to access B's properties i found out i can only access variables or methods from class A even though i made an object of type B.

I thought that this was only relevant if both classes didnt have the same methods or variables. But in this case both classes have a variable named w yet i can only access the value stored in the A class. Why is this so?

class A


public class A {
    public int w;
    private static String str = "K";

    
    public A() {
        str ="B";
        w =str.length();
        str =w;
    }
    
    @Override
    public String toString() {
        return str.charAt(w-2) "P";
    }
    

}

class B

public class B extends A {
    public static int w = 2;
    private String str = "W";
    
    public B(int x) {
        w =super.w;
        str =super.toString() w;
    }
    
    @Override
    public String toString() {
        return super.toString()   str;
    }
}

Testing class


public class Q1 {

    public static void main(String[] args) {
        A a = new A();
        A a2 = new B(1);

        System.out.println(a);
        System.out.println(a.w);
        System.out.println(a2);
        System.out.println(a2.w);
        B b = new B(2);
        System.out.println(b);
    }

}

CodePudding user response:

Since the type of variable a is [class] A, the variable can only access members and methods of class A (depending on the access specifiers) – even though the actual type of variable a is class B.

Refer to method paintComponent, in class javax.swing.JComponent. The type of the method parameter is Graphics but the actual type of the parameter is Graphics2D (which extends Graphics). However, in order to access the methods of Graphics2D, you must first cast the parameter, i.e.

Graphics2D g2d = (Graphics2D) g;

This is a fundamental aspect of the object-oriented paradigm.
Refer also to the comment to your question by @ArunSudhakaran

Similarly, if you want variable a to access the w member of class B, you need to cast a.

A a = new B();
if (a instanceof B) {
    B b = (B) a;
    System.out.println(b.w);
}

If you are using at least Java 14, you can use Pattern Matching for the instanceof Operator

A a = new B();
if (a instanceof B b) {
    System.out.println(b.w);
}

Also refer to the book Effective Java by Josh Bloch.

CodePudding user response:

As you are doing Type Casting so this is normal behaviour of inheritance. You may check this link

  • Related