Constant Issues in Java inheritance

Source: Internet
Author: User

This is the Super class Human:

class Human {    = "Human";     = "humanity";      Public String Gethuman () {        returnthis. name+ ";" +this. sex+ ";" ;    }}

These and his subclasses:

 class  man extends   human{String name  = "Adam" ;    String sex  = "Male" ;        Man (String name) { this . Name = name; System.out.println ( this . name+ ";" +this . sex+ ";"    ); }}
class extends human{    = "Eva";     = "Female";    Woman (String name) {        this. Name= name;        System.out.println (this. name+ ";" +this. sex+ ";" );    } }

And this is the test main function:

 Public class objecttest {    publicstaticvoid  main (string[] args) {        new  Human ();         New Woman ("Kate");         New Man ("Jim");        System.out.println (Kate.gethuman ()+jim.gethuman () +Human.gethuman ());}    }

The final result is:

Kate; Female;
Jim; Male;
Human; Humanity; Human; Humanity; Human; Humanity;

So, this is the problem. As we know, the override in Java makes us can rewrite the method of super class in its subclass. However, we can ' t override the content in the Super class. When the content in subclass have the same name, the Origin content in super class would been hidden in the subclass. By the time there is actually the contents who has the same name in the subclass! When we use the method in super class, the method would still invoking the Super class ' Origin content.

So, the conclusion is the and we should try to avoid operating content in the process of inherit. Use Setters and getter method instead to manipulate the content are much more safer and reasonable.

Constant Issues in Java inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.