how change in child class instance variable also changes val

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
RRRRRR
Posts: 26
Joined: Sun Jul 23, 2017 2:13 am
Contact:

how change in child class instance variable also changes val

Post by RRRRRR »

class Feline {
public String type = "f ";
public Feline() {
System.out.print("feline ");
}
}
public class Cougar extends Feline {
public Cougar() {
System.out.print("cougar ");
}
void go() {
type = "c ";
System.out.print(this.type + super.type);
}
public static void main(String[] args) {
new Cougar().go();
}
}


In above code we have changed value of the inherited variable ("type") inherited from parent class from 'f' to 'c' . So (this.type) gives current class instance variable("type") value which is 'c' , because we change it inside method go() . OK , but why that change is also reflected in parent class since (super.type) also gives 'c' . But How.How change in child class instance variable also changes value of base class instance variable ?

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: how change in child class instance variable also changes

Post by admin »

Because there is only one 'type' in Couger, the one that it inherited from base class. Inheriting a field doesn't mean that now you have two copies (parent + child) of the same field.
If you like our products and services, please help us by posting your review here.

RRRRRR
Posts: 26
Joined: Sun Jul 23, 2017 2:13 am
Contact:

Re: how change in child class instance variable also changes

Post by RRRRRR »

THANKS :thumbup:

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 39 guests