Reputation: 35
As in the concept of Inheritance, I went through the process of accessing child class members with the parent class instance but it is not working as excepted by raising error. My code is as below :
package base;
public class p {
String college = "vrce";
void does() {
System.out.println("student");
}
}
public class c extends p {
String branch = "ece";
public static void main(String[] args) {
/*c o= new c();
System.out.println(o.college);
System.out.println(o.branch);
o.does();
all child and parent work*/
p o = new c(); ////c p
System.out.println(o.college);
System.out.println((o.branch));
o.does();
/* p o= new p();
System.out.println(o.college);
// System.out.println(o.branch);//child details can't
o.does();*/
}
}
As shown above p
class is parent and c
is child class and I want to access the child member branch
with the parent class instance as p o = new c();
.
If it is possible, how is it possible? If not, then why is it not possible. Please explain me in details? Thanks in advance.
Upvotes: 0
Views: 1163
Reputation: 98
This will not work because Class p
does not have a field of branch
. You could cast it to c
then get branch from it as o
is an instance of c
, ((c)o).branch
. This would work because you know o
is an instance of c
. (i.e. p o= new c();
)
As @NickJ mentioned, class names and variables should be more verbose/descriptive than p
, c
(Classes generally start with a capital letter, like Parent
or Child
)
Upvotes: 0
Reputation: 9559
Since you have a reference to class p
, the Parent class, you can only access methods and fields defined by the parent class.
If you need to access methods and fields defined by the child class, you need to cast it:
System.out.println((c) o.branch);
TIP: p
and c
are not good names for classes. Best to use descriptive words. In this example, even Parent
and Child
would have been better.
Upvotes: 2