Java inheritance

await 2021-09-15 07:22:29
java inheritance


{tabs-pane label="private"}

Inheritance is a very powerful mechanism in object-oriented programming , It can first reuse code . When we let Student2 from Student inheritance ,Student2 You get it Student All functions of , We just need to Student2 Write new functions . By inheritance ,Student2 Just write additional functions , There is no need to repeat the code .

stay OOP In terms of , We put Student It's called superclass (super class), Parent class (parent class), Base class (base class), hold Student2 Called subclass (subclass), The extension class (extended class).

Java Only one is allowed class Inherited from a class , therefore , A class has and only has one parent class . Only Object special , It has no parent class .

Student stu=new Student();
stu.setName("admin");
System.out.println(stu.getName());
Student2 stu2=new Student2();
stu2.setName("admin");
stu2.setAge(123);
stu2.setClas("Iot1903");
stu2.setId(1001);
System.out.println(stu2.getName()+" "+stu2.getAge()+" "+stu2.getclas()+" "+stu2.getId());
// Inherit
class Student{
private String name;
private int age;
private String clas;
public String getName(){return this.name;}
public void setName(String name){this.name=name;}
public int getAge(){return this.age;}
public void setAge(int age){this.age=age;}
public String getclas(){return this.clas;}
public void setClas(String clas){this.clas=clas;}
}
class Student2 extends Student{
// Inherited Student All the functions in , We just need to add new features
private int id;
public int getId(){return this.id;}
public void setId(int id){this.id=id;}
} 

{/tabs-pane} {tabs-pane label="private effect "}

{/tabs-pane}

{tabs-pane label="protected"} Inheritance has a characteristic , Is that the child class cannot access the parent class Student Field or private Method . for example ,Student2 Class cannot access Student Class name and age word , This weakens the role of inheritance . In order for the subclass to access the fields of the parent class , We need to take private Change it to protected. use protected The decorated fields can be accessed by subclasses :

class Student {
protected String name;
protected int age;
}
class Student2 extends Student {
public String hello() {
return "Hello, " + name; // OK!
}
}

therefore ,protected Keywords can control the access rights of fields and methods within the inheritance tree , One protected Fields and methods can be subclassed , And the subclass of the subclass . {/tabs-pane} {tabs-pane label="super"} super Keyword represents parent class ( Superclass ). When a subclass references a field of a parent class , It can be used super.fieldName.

class Student2 extends Student {
public String hello() {
return "Hello, " + super.name;
}
}
// Use here super.name, perhaps this.name, perhaps name, The effect is the same . The compiler will automatically locate the parent class name Field .

At some point , Must use super

public class Main {
public static void main(String[] args) {
Student2 s = new Student2("lq", 12, 89);
}
}
class Student {
protected String name;
protected int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Student2 extends Student {
protected int score;
public Student(String name, int age, int score) {
// Because in Java in , whatever class Construction method of , The first line of statements must call the constructor of the parent class . If the constructor of the parent class is not explicitly called , The compiler will automatically add a sentence for us super();
//super(); Because in Student There is no parameterless constructor in class , So this sentence will report an error Should be replaced by the following :
super(name,age);
this.score = score;
}
}

If the parent class does not have a default constructor , Subclasses must explicitly call super() And give the parameters so that the compiler can locate a suitable construction method of the parent class . That is, the subclass does not inherit any of the parent's construction methods . The default constructor for subclasses is generated automatically by the compiler , It's not inherited .

{/tabs-pane} {tabs-pane label="final"} final Subclasses are not allowed to override methods of the parent class

 final Modified classes cannot be inherited final class Student{} uninheritable
final Modified fields cannot be modified after initialization ,
public final String name=" I can't be modified ";
Fields can be initialized in the constructor
Ensure that once the instance is created , Its final The field cannot be changed 
// Class cannot be inherited
final class Student {
protected String name;
}
// Methods cannot be overridden by subclasses
class Student {
protected String name;
public final String hello() {
return "Hello, " + name;
}
}
Student extends Student {
// compile error: Override not allowed
@Override
public String hello() {
}
}
class Student {// Field
public final String name = "Unamed";
}
// Field reassignment
Student p = new Student();
p.name = "New Name"; // compile error!

{/tabs-pane}

This article altogether 635 Number of words , Average reading time ≈ 2 minute

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[await]所创,转载请带上原文链接,感谢
https://javamana.com/2021/09/20210909125824200p.html

  1. Design pattern -- agent pattern
  2. Huawei Java Senior Engineer interview question, Byte Jumping thousand Selected Interview Question is still not Brushed!
  3. 双非本科字节跳动Java面试题分享,一篇文章教你搞定计算机网络面试,
  4. 又到一年金三银四,2021最新Java笔试题及答案,
  5. Huawei Finance and Economics 2021 Spring Recruitment interview, what is distributed Lock?Pourquoi utiliser des serrures distribuées?
  6. Un an plus tard, Golden, Silver, Silver, and Silver, 2021, the latest Java written Examination Questions and Answers,
  7. Partage de questions d'entrevue Java à double saut d'octets non - premier cycle, un article vous apprend à gérer l'entrevue réseau informatique,
  8. Computer graduation project java online voting system based on SSM
  9. K8s gestion des ressources (opérations de base)
  10. 又到一年金三銀四,2021最新Java筆試題及答案,
  11. Collection de code de base JavaScript (1)
  12. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  13. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  14. Cloud Security Daily 210914: Red Hat Jboss Middleware Platform found important Security Vulnerability and needs to be upgraded as soon as possible
  15. 吐血整理,腾讯团队实力打造spring入门教程,
  16. 史上最全的微服务专业术语面试50问,字节跳动Java岗经典面试真题,
  17. Absolument!C'est l'analyse la plus détaillée du code source de hashtap que j'ai jamais vu!
  18. Computer graduation project Java logistics order management system of logistics company based on SSM
  19. Talk about Kafka: source code analysis of producer
  20. [springboot2 starts from 0] development tips - Lombok, devtools, spring initailizr
  21. 国内一线互联网公司面试题汇总,2021年大厂Java岗面试必问,
  22. 啃完吃透保你涨薪5K,熬夜整理小米Java面试题,
  23. 和字节跳动大佬的技术面谈,Redis成神之路电子版教程已问世,
  24. Le terme professionnel le plus complet de l'histoire des micro - services interview 50 questions, Byte Jumping Java post Classic interview vrai problème,
  25. After using mybatisplus, I haven't written SQL for a long time
  26. [springboot2 starts from 0] how to write a springboot application?
  27. Huawei cloud guassdb (for redis) released a new version, and the two core features were officially unveiled
  28. 和字節跳動大佬的技術面談,Redis成神之路電子版教程已問世,
  29. 啃完吃透保你漲薪5K,熬夜整理小米Java面試題,
  30. Avec l'interview technique du gigolo, le tutoriel électronique redis est sorti.
  31. Après avoir mangé, assurez - vous d'augmenter votre salaire de 5K et de rester debout tard pour trier les questions d'entrevue Java de millet.
  32. Résumé des questions d'entrevue pour les entreprises Internet nationales de première ligne, qui doivent être posées lors de l'entrevue d'emploi Java de la grande usine en 2021,
  33. Le tri des crachats de sang, la force de l'équipe Tencent pour créer le tutoriel d'introduction au printemps,
  34. Java and scala concurrency Fundamentals
  35. Analysis of java thread source code based on Hotspot
  36. 國內一線互聯網公司面試題匯總,2021年大廠Java崗面試必問,
  37. Introduction au module de contrôle de Connexion MySQL
  38. 大厂高级测试面试题,Java面试基础技能罗列,
  39. Comprendre l'architecture sous - jacente d'InnoDB en exécutant une instruction
  40. Chargeur de classe 1 Tomcat
  41. 小白也能看懂的dubbo3应用级服务发现详解
  42. SpringBoot异步使用@Async原理及线程池配置
  43. Questions d'entrevue de test avancé de Dachang, liste des compétences de base de l'entrevue Java,
  44. SpringBoot异步使用@Async原理及線程池配置
  45. Springboot utilise asynchrone le principe @ async et la configuration du pool de threads
  46. Détails de la découverte du Service d'application Dubbo 3 que Xiaobai peut également comprendre
  47. Springboot utilise asynchrone le principe @ async et la configuration du pool de threads
  48. 如何强大且优雅的搞定Linux文件系统,算法题 JVM,
  49. 太牛了,阿里P7架构师带你看透maven的来龙去脉,
  50. Oracle central et Oracle décentralisé
  51. java JavaBean
  52. Java wrapper type
  53. Java super keyword
  54. Java static keyword
  55. Java this keyword
  56. Java interface
  57. 太牛了,阿裏P7架構師帶你看透maven的來龍去脈,
  58. C'est génial, l'architecte Ali p7 vous montre à travers Maven.
  59. Comment traiter le système de fichiers Linux avec puissance et élégance, algorithme JVM,
  60. Usage of Java scanner