About subclass member variables in Java with the same name as the parent class member variable __java

Source: Internet
Author: User

Overrides and overloads are for methods, and the variables of subclasses can overwrite the variables of the parent class, but cannot change the parent class's variables.


Class Animals {
	int age = ten;
	void Enjoy () {
		System.out.println ("Animals enjoy!");
	}

Class Dogg extends Animals {
	int age =;
	int weight;
	void Enjoy () {
		System.out.println ("Dog enjoy!");
	}

public class Testduotai {public
	static void Main (string[] args) {
		Animals a = new Animals ();
		A.enjoy ();
		System.out.println (a.age);
		
		Dogg d = new Dogg ();
		D.enjoy ();
		System.out.println (d.age);
		
		Animals D1 = new  Dogg ();
		D1.enjoy ();		
		System.out.println (d1.age);
		Dogg s = (Dogg) d1;
		System.out.println (s.age);
		
	}

Print results:

Animals enjoy!
10
Dog enjoy!
20
Dog enjoy!
10
20

This shows that the variables of the parent class and subclass exist concurrently, even with the same name.
You see a subclass of a variable in a subclass, and in the parent class you see a variable in the parent class.
They are hidden from each other, and methods with the same name are real overrides (Overrides).


such as animals D1 = new Dogg ();
D1 is a animals object and a Dogg object,
When the method is invoked, it is called based on the actual type of the object, and
the actual type is Dogg, so the method of calling the subclass is always invoked.

and access to the member variable is different, it is animals, access to the parent class of the member variable,
transformation to Dogg, the access is the subclass of the member variable.

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.