Monday, 15 February 2010

java - NullPointerException when using inheritence -


I have a scenario that can be best according to the following toy example. Let me assume that I have four squares:

  public square animal {public animal (string a_name) {this.name = a_name; } Name of the public string; } Public class mammal animal {public mammal (string a_name, string a_nickname) {super (a_name) extends; This.nick_name = a_nickname; } String nick_name; } Public square Animal_Groomer {Public Animal_Groomer (animal an_animal) {this.the_animal = an_animal; } Public Zero print_name () {System.out.println (the_animal.name); } Public animal the_animal; } Public class mammals expand animal animal grammar {public mammal group (mammalian one_mammal) {super (one_mammal); } Public Zero print_nickname () {System.out.println (the_animal.nick_name); } Public mammals the_animal; }  

Now that I have a main routine

  mammals a_mammal = new mammal ("Tiger", "Bob"); Mammalian Housewife MG = New Mammals (Group); MG.print_name (); MG.print_nickname ();  

MG.print_name () Output "Tiger", but MG.print_nickname () provides me a java.lang.NullPointerException exception. Is there any way to fix the constructor or MG.print_nickname () method to print nick_name? Thank you.

In heritage, fields and static members are swapped on methods when hidden / hidden.

So if you start an area in the parents, then there will be no effect on the child if you define the same area in the child because this shadow will appear.

You are not starting the child's area to hide the area of ​​your parents and its value is null you have to start different child class members in the child's conservator is required.

  public mammal_groomer (mammalian a_mammal) {super (a_mammal); This.the_animal = a_mammal; }  

Read more about shading / hiding and override:


No comments:

Post a Comment