Learning Java here and I try to cast on a super class and i cant access to subclass methods, is it possible, I am doing something wrong.
I have this:
public class Musician {
public String name;
public String surname;
}
public class Instrumentist extends Musician{
public String getInstrumento() {
return instrumento;
}
public void setInstrumento(String instrumento) {
this.instrumento = instrumento;
}
private String instrumento;
public Instrumentist(String nombre, String name, String surname){
this.name = nombre;
this.surname = surname;
}
}
public class Main {
public static void main(String[] args) {
Musician m = new Instrumentist("Antonio", "Vivaldi", "none");
System.out.println(m);
}
}
I know I can do Instrumentist i = new Instrumentist("Antonio", "Vivaldi", "none")
but then what is the purpose of Cast to superclass?
The concept is like this:
The superclass/interface provides general implementation or a contract. The subclass overrides/implements that contract.
To make sure that you can assign different implementations of that contract at runtime, you use reference of a Superclass and assign object of a subclass to it.
Musician m = new Instrumentist("Antonio", "Vivaldi", "none");
Here, with m, you can call methods defined in Musician class, but if your subclass has any other methods apart from those defined superclass, you can not access them using m. If subclass overrides any method, then even after using reference of superclass, say m, java would make sure that at runtime, overridden method in subclass is called.
This code prints "GenericAnimal", where as I was expecting it to print "PolymorphismTest" as I created an object of PolymorphismTest.
class GenericAnimal{
String name="GenericAnimal";
}
public class PolymorphismTest extends GenericAnimal {
String name = "PolymorphismTest";
public static void main(String[] args) {
GenericAnimal animal = new PolymorphismTest();
System.out.println(animal.name);
}
}
It's called field "hiding" or "shadowing". You have a second field of the same name as the field in the parent class. If the one in the parent were private then it would not be accessible to the subclass.
The extra String name field in the subclass occupies its own memory and reference. You probably should re-use the field of the parent class by either making it visible (i.e. protected or public scope) or adding a protected or public accessor and mutator to the parent class that the subclass can invoke to access and manipulate the field.
Because you're accessing the field, rather that a function. The second field shadows the one in the superclass, rather than overriding. This is not the same as the behaviour of functions, which is probably what you were looking for here:
class GenericAnimal {
String name = "GenericAnimal";
public String getAnimal(){
return name;
}
}
public class PolymorphismTest extends GenericAnimal {
String name = "PolymorphismTest";
public static void main(String[] args) {
GenericAnimal animal = new PolymorphismTest();
System.out.println(animal.name);
System.out.println(animal.getAnimal());
PolymorphismTest testAnimal = (PolymorphismTest)animal;
System.out.println(testAnimal.name);
System.out.println(testAnimal.getAnimal());
}
public String getAnimal(){
return name;
}
}
Your GenericAnimal reference cannot reference to the property of its subclass PolymorphismTest. Property values cannot be overridden in java, only the methods.
Note:
This is NOT about hiding at all. (That would be the other direction of reference.)
How would I initialise the string name and the instance variable named right in the superclass to true from the HighRights class?
So if high is an instance of HighRights then
high.getSecret();
should return the secret is 42
public class SecurityRights {
private boolean right;
private boolean canreadSecret;
String SECRET="the secret is 42";
public SecurityRights(boolean r) {
right =r;
if (r) canreadSecret=true; else canreadSecret=false;
}
boolean getRight(){
return right;
}
boolean canReadSecret(){
return canreadSecret;
}
String getSecret(){
if (canreadSecret) return SECRET; else return "access denied";
}
}
public class HighRights extends SecurityRights
{
private String name;
public HighRights(String n){
}
public String getName(){
return name;
}
public static void main(String[] a){
HighRights s= new HighRights("Lisa");
System.out.print(s.getName() +" "+s.getSecret());
}
}
You call the Parent's constructor by calling super().
So in your case
super(booleanValue);
Usually, this would be placed in the first line of your child constructor.
You could also change the privacy level from private to protected, and then you would be able to access it in all child objects.
You can either make a method just like you did when calling getSecret() and intialize and boolean and string.
OR
you can use the super methods. Here is some more info. You would pretty much be making a constructor for the class, but since an instance of the class is never really created only a Child of that instance, you need to use the super command to make constructors.
The inherited class would have the following implementation:-
class HighRights extends SecurityRights
{
private String name;
public HighRights(boolean r,String n){
super(r);
this.name = n;
}
public String getName(){
return name;
}
public static void main(String[] a){
HighRights s= new HighRights(false,"Lisa");
System.out.print(s.getName() +" "+s.getSecret());
}
}
In this implementation, the super keyword is used. super keyword is used when you need to call the superclass's constructor from the constructor of the subclass. Since you needed to access the right variable of SecurityRights from the constructor of HighRights, you could access it by using the super keyword. More information can be found at oracle's manual.
Also, you gave an argument in the constructor of SecurityRights but you didn't assign it to any variable. Please avoid these mistakes.
I just started to learn Java, so please bear with me if the answer is somewhat obvious. I did some research but no avail.
From what I understand, attributes are not overriden but only field hidden. To determine whether the attribute in the superclass or the subclass is used, Java will check the type of the reference.
Then I don't under stand the output here:
public class Super {
String str = "I'm super!\n";
public String toString() {
return str;
}
}
public class Sub extends Super {
String str = "I'm sub.\n";
}
public class TestFH {
public static void main(String[] args) {
Sub s1 = new Sub();
System.out.printf(s1.toString());
}
}
It gives me:
I'm super!
I understand that I can achieve what I want easily via method overriding. I'm just curious about what's happenning under the hood.
Thanks in advance.
When you call, s1.toString(), it's finding toString() method defined only in Super class hence using that method as super class methods are available in the sub class. Your super class method toString() is using it's own class variable str (with value initialized in super class) as the return value from the method and hence the behavior i.e. output as I'm super!.
If you want to get the output as I'm sub.\n then you need to reuse the same variable as in the super class and assign the new string value i.e. I'm sub.\n to it. Best option is to use constructors as:
public class Super {
String str = "I'm super!\n";
public Super(String stringValue){
this.str = stringValue;
}
public String toString() {
return str;
}
}
public class Sub extends Super {
public Sub(){
super("I'm sub.\n");
}
}
public class TestFH {
public static void main(String[] args) {
Sub s1 = new Sub();
System.out.printf(s1.toString());
}
}
You're hiding (shadowing) str in your child class. Since you have not overridden toString() in your child class, the call is being made in the parent class, and it sees the parent's str.
If you did this:
public class Sub extends Super {
public Sub() {
this.str = "I'm sub.\n";
}
}
It would output what you're expecting.
This call is using the super class:
Sub s1 = new Sub();
System.out.printf(s1.toString());
The reason is that Sub is not overriding str, it is just declaring another variable that happens to have the same name. In other words, sub is just hiding the variable in Super (data members are not polymorphic).
You could give them different names if they mean different things. Or maybe have the Sub access (or modify) the parent's attribute using a getter method.
you're not assigning the string literal, "I'm sub.\n" to the shared superclass field, you're creating a field local to the subclass and assigning it to that instead.
for example,
public class EncapsulationDemo {
public static void main(String[] args){
MySuperObject obj = new MySubObject();
System.out.println(obj); // prints I'm sub.
}
private static class MySuperObject{
String str = "I'm super."; // protected, can be accessed directly
// by subclasses
#Override
public String toString(){
return str;
}
}
private static class MySubObject extends MySuperObject{
MySubObject(){
super();
str = "I'm sub."; // assign to superclass field
}
}
}
for more information, please see Controlling Access to Members of a Class.
This is a question I was asked in an interview: I have class A with private members and Class B extends A. I know private members of a class cannot be accessed, but the question is: I need to access private members of class A from class B, rather than create variables with the same value in class B.
The interviewer was either testing your knowledge of access modifiers, or your approach to changing existing classes, or both.
I would have listed them (public, private, protected, package private) with an explanation of each. Then gone on to say that class A would need to be modified to allow access to those members from class B, either by adding setters and getters, or by changing the access modifiers of the members. Or class B could use reflection. Finally, talk about the pros and cons of each approach.
Reflection? Omitting imports, this should work:
public class A {
private int ii = 23;
}
public class B extends A {
private void readPrivateSuperClassField() throws Exception {
Class<?> clazz = getClass().getSuperclass();
Field field = clazz.getDeclaredField("ii");
field.setAccessible(true);
System.out.println(field.getInt(this));
}
public static void main(String[] args) throws Exception {
new B().readPrivateSuperClassField();
}
}
It'll not work if you do something like that before the of invocation readPrivateSuperClassField();:
System.setSecurityManager(new SecurityManager() {
#Override
public void checkMemberAccess(Class<?> clazz, int which) {
if (clazz.equals(A.class)) {
throw new SecurityException();
} else {
super.checkMemberAccess(clazz, which);
}
}
});
And there are other conditions under which the Reflection approach won't work. See the API docs for SecurityManager and AccessibleObject for more info. Thanks to CPerkins for pointing that out.
I hope they were just testing your knowledge, not looking for a real application of this stuff ;-) Although I think an ugly hack like this above can be legit in certain edge cases.
The architecture is broken. Private members are private because you do not want them accessed outside the class and friends.
You can use friend hacks, accessors, promote the member, or #define private public (heh). But these are all short term solutions - you will probably have to revisit the broken architecture at some stage.
By using public accessors (getters & setters) of A's privates members ...
You cannot access private members from the parent class. You have make it protected or have protected/public method that has access to them.
EDIT : It is true you can use reflection. But that is not usual and not good idea to break encapsulation.
A nested class can access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
public class SuperClass
{
private int a = 10;
public void makeInner()
{
SubClass in = new SubClass();
in.inner();
}
class SubClass
{
public void inner()
{
System.out.println("Super a is " + a);
}
}
public static void main(String[] args)
{
SuperClass.SubClass s = new SuperClass().new SubClass();
s.inner();
}
}
If I'm understanding the question correctly, you could change private to protected. Protected variables are accessible to subclasses but behave like private variables otherwise.
By using setters and getters u can access it
From JLS §8.3. Field Declarations:
A private field of a superclass might be accessible to a subclass - for example, if both classes are members of the same class. Nevertheless, a private field is never inherited by a subclass.
I write the example code:
public class Outer
{
class InnerA
{
private String text;
}
class InnerB extends InnerA
{
public void setText(String text)
{
InnerA innerA = this;
innerA.text = text;
}
public String getText()
{
return ((InnerA) this).text;
}
}
public static void main(String[] args)
{
final InnerB innerB = new Outer().new InnerB();
innerB.setText("hello world");
System.out.println(innerB.getText());
}
}
The explanation of the accessibility of InnerA.text is here JLS §6.6.1. Determining Accessibility:
Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
You can use the setters and getters of class A. Which gives same feeling as if You are using a class A's object.
Have you thought about making them protected ? Just to be sure you are aware of this option, if you are then pardon me for bringing up this trivia ;)
Private members cant be accessed in derived class
If you want to access means you can use getter and setter methods.
class A
{
private int a;
void setA(int a)
{
this.a=a;
}
int getA()
{
return a;
}
}
Class B extends A
{
public static void main(String[] arg)
{
B obj= new B();
obj.setA(10);
System.out.println("The value of A is:"+obj.getA());
}
}
Private will be hidden until you have been given the right access to it. For instance Getters or setters by the programmer who wrote the Parent. If they are not visible by that either then accept the fact that they are just private and not accessible to you. Why exactly you want to do that??
I don't know about Java, but in some languages nested types can do this:
class A {
private string someField;
class B : A {
void Foo() {
someField = "abc";
}
}
}
Otherwise, use an accessor method or a protected field (although they are often abused).
A private member is accessible in subclass in a way that you cannot change the variable, but you are able to access the variable as read only.
Obviously, making them protected, or adding setters/getters is the preferred technique. Reflection is a desperation option.
Just to show off to the interviewer, IF "access" means read access, and IF Class A generates XML or JSON etc., you could serialize A and parse the interesting fields.
Class A
{
private int i;
int getValue()
{
return i;
}
}
class B extends A
{
void getvalue2()
{
A a1= new A();
sop(a1.getValue());
}
}
To access private variables of parent class in subclass you can use protected or add getters and setters to private variables in parent class..
You can't access directly any private variables of a class from outside directly.
You can access private member's using getter and setter.
Ways to access the superclass private members in subclass :
If you want package access just change the private fields to protected. It allows access to same package subclass.
If you have private fields then just provide some Accessor Methods(getters) and you can access them in your subclass.
You can also use inner class e.g
public class PrivateInnerClassAccess {
private int value=20;
class InnerClass {
public void accessPrivateFields() {
System.out.println("Value of private field : " + value);
}
}
public static void main(String arr[])
{
PrivateInnerClassAccess access = new PrivateInnerClassAccess();
PrivateInnerClassAccess.InnerClass innerClass = access.new InnerClass();
innerClass.accessPrivateFields();
}
}
4 .You can also use Reflection e.g
public class A {
private int value;
public A(int value)
{
this.value = value;
}
}
public class B {
public void accessPrivateA()throws Exception
{
A a = new A(10);
Field privateFields = A.class.getDeclaredField("value");
privateFields.setAccessible(true);
Integer value = (Integer)privateFields.get(a);
System.out.println("Value of private field is :"+value);
}
public static void main(String arr[]) throws Exception
{
B b = new B();
b.accessPrivateA();
}
}
You can use Accessors (getter and setter method) in your Code.
By using setter method you can use else with the help of refection you can use private member of class by setting that member say a -
take a from class
and set a.setAccessible(true);
You may want to change it to protected.
Kindly refer this
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If this is something you have to do at any cost just for the heck of doing it you can use reflection. It will give you list of all the variables defined in the class- be it public, private or protected. This surely has its overhead but yes, it is something which will let you use private variables. With this, you can use it in any of the class. It does not have to be only a subclass
Please refer to the example below. This may have some compilation issues but you can get the basic idea and it works
private void getPropertiesFromPrivateClass(){
Field[] privateVariablesArray = PrivateClassName.getClass().getDeclaredFields();
Set<String> propertySet = new HashSet<String>();
Object propertyValue;
if(privateVariablesArray.length >0){
for(Field propertyVariable :privateVariablesArray){
try {
if (propertyVariable.getType() == String.class){
propertyVariable.setAccessible(true);
propertyValue = propertyVariable.get(envtHelper);
System.out.println("propertyValue");
}
} catch (IllegalArgumentException illegalArgumentException) {
illegalArgumentException.printStackTrace();
} catch (IllegalAccessException illegalAccessException) {
illegalAccessException.printStackTrace();
}
}
Hope this be of some help.
Happy Learning :)
Below is the example for accessing the private members of superclass in the object of subclass.
I am using constructors to do the same.
Below is the superclass Fruit
public class Fruit {
private String type;
public Fruit() {
}
public Fruit(String type) {
super();
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Below is subclass Guava which is inheriting from Fruit
public class Guava extends Fruit{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Guava(String name,String type) {
super(type);
this.name=name;
}
}
Below is the main function where we are creating an object of subclass and also displaying the member of superclass.
public class Main {
public static void main(String[] args) {
Guava G1=new Guava("kanpuria", "red");
System.out.println(G1.getName()+" "+G1.getType());
}
}
Note that a private field of a superclass might be accessible to a subclass (for example,if both classes are memebers of the same class),Nevertheless,a private field is never inherited
by a subclass
Simple!!!
public class A{
private String a;
private String b;
//getter and setter are here
}
public class B extends A{
public B(String a, String b){ //constructor
super(a,b)//from here you got access with private variable of class A
}
}
thanks
Directly we can't access it. but Using Setter and Getter we can access,
Code is :
class AccessPrivate1 {
private int a=10; //private integer
private int b=15;
int getValueofA()
{
return this.a;
}
int getValueofB()
{
return this.b;
}
}
public class AccessPrivate{
public static void main(String args[])
{
AccessPrivate1 obj=new AccessPrivate1();
System.out.println(obj.getValueofA()); //getting the value of private integer of class AccessPrivate1
System.out.println(obj.getValueofB()); //getting the value of private integer of class AccessPrivate1
}
}
Modifiers are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following:
Java Access Modifiers
Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement.
There is more information here:
http://tutorialcorejava.blogspot.in/p/java-modifier-types.html