日期:2025/04/06 15:52来源:未知 人气:54
分享兴趣,传播快乐,增长见闻,留下美好!
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来
“Java子类与继承(一)”
欢迎您的访问。
Share interest, spread happiness, increase knowledge, and leave beautiful.
Dear, this is the LearingYard Academy!
Today, the editor brings the
Java Subclasses and Inheritance (1),
Welcome to visit!
Java子类与继承(一)
01:32来自LearningYard学苑
一、子类与父类
Java中子类是一个很神奇的类,它继承父类,避免重复声明成员变量和方法,也能使整个编程逻辑清晰。
Java subclass is a very magical class, it inherits the parent class, avoids repeated declarations of member variables and methods, but also makes the entire programming logic clear.
子类的声明很简单,只需记住一个单词,extend,用的时候是第三人称单数形式,即extends。当然,不要忘了说明一下继承的对象,即父类。所以,子类的声明只需在声明的类后面加上extends +父类类名。
The declaration of a subclass is as simple as remembering one word, extend, when used in the third person singular, extends. Of course, don't forget to mention the inherited object, the parent class. So, a subclass declaration simply follows the declared class with the extends + parent class name.
Java中有一个祖先类Object,我们在程序中建的类实际都是这个类的子类,只是一般可以省略继承Object类的语句,如我们声明一个A类,写成class A,实际上就是class A extends Object。
Java has an ancestor class Object, and the classes we build in our programs are actually subclasses of this class, except that we can generally omit statements that inherit Object class, for example, if we declare A class A, as class A, it is actually class a extends Object.
二、子类的继承
子类和父类同包时,可以继承除被private修饰的以外的成员变量和方法。下面,我写了一个People类,和一个People的子类Student类。人有名字有年龄,学生除姓名、年龄外,还有学号。主类中定义叫小明的人和叫李华的学生,输出小明和李华的名字,我们可以发现Student类中并没有声明name和showName的方法,但李华仍能调用方法输出名字说明Student类确实继承了People类中的成员变量和方法。
When a subclass and parent class are in the same package, they can inherit member variables and methods except those that are privately modified. Below, I wrote a class of People, and a subclass of People, the Student class. People have names and ages, and students have student numbers in addition to names and ages. The main class defines a person named Xiaoming and a Student named Li Hua, and outputs the names of Xiaoming and Li Hua. We can find that the Student class does not declare the method name and showName, but Li Hua can still call the method output name, indicating that the Student class does inherit the member variables and methods in the People class.
那如果我不想让子类继承名字这一成员变量呢。那么就可以用private修饰name。修改后,第23行的name不能直接用了,就报错了,说明子类没有继承到name这个成员变量。
What if I don't want the subclass to inherit the name as a member variable. So you can use private to modify the name. After the modification, the name in line 23 cannot be used directly, and an error is reported, indicating that the subclass does not inherit the name member variable.
今天的分享就到这里了,
如果您对文章有独特的想法,
欢迎给我们留言。
让我们相约明天,
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!
参考资料
翻译:网易有道翻译
本文由LearningYard学苑整理并发出,如有侵权请后台留言沟通.
文案|Dongyang
排版|Dongyang
审核|yue
Learning Yard 新学苑
下一篇:Java:类与继承