Pandiyan Cool
Pandiyan Cool

Reputation: 6585

Accessing values from other class and how to access base class variable

I have tried some codes in java to access variables, my code is as follows

class FirstClass {
    public String className = "FirstClass";
    int arg=100;
    private String insideVariable="Private";
}
class SecondClass extends FirstClass{
    public String className="SecondClass";
    public String extend=new FirstClass().className;
}

public class Access {
    public static void main(String[] args) {
        System.out.println(new FirstClass().className);
        System.out.println(new SecondClass().className);
        System.out.println(new SecondClass().arg);
        System.out.println(new SecondClass().extend);
    }
}

I have following questions,

  1. I can able to access className variable values by using new FirstClass.className and new SecondClass().className, Is this creates object or what is the functions happen here?

  2. I'm extending the FirstClass to SecondClass, and i can able to access arg variable using new SecondClass().arg, now how to access the className variable in Base class using extended class?

Upvotes: 1

Views: 162

Answers (2)

Henry
Henry

Reputation: 43798

From outside, you can cast to the base type to access the field:

System.out.println(((FirstClass)new SecondClass()).className);

Upvotes: 2

bash.d
bash.d

Reputation: 13217

In 1. you are creating anonymous instances using new and you access their member className.
In 2. you can use super.className INSIDE your derived class.

class SecondClass extends FirstClass{
    public String className="SecondClass";
    public String extend=new FirstClass().className;

    public void method() {
        String cn = super.className;
    }
}

Apart from this possibilities, you are grinding OO-principle of data-hiding to pieces. If you want to access a base-class member, either make the base-class member protected or create getter/setter-methods.

Upvotes: 3

Related Questions