Java Basics - inheritance

Write code to change Basin 2021-02-23 17:47:08
java basics inheritance


Access right

Java There are three access modifiers in :private、protected as well as public, If you do not add an access modifier , Indicates package-level visibility .

You can pair a class or a member of a class ( Fields and methods ) Add an access modifier .

  • Class visibility means that other classes can use this class to create instance objects .
  • Member visibility means that other classes can access that member with instance objects of that class ;

protected Pertaining to members , Means that members are visible to subclasses in the inheritance system , But this access modifier has no meaning for the class .

A well-designed module hides all the implementation details , It's API It is clearly separated from its implementation . Modules pass between them only API communicate , A module does not need to know the inner workings of other modules , This concept is called information hiding or encapsulation . Therefore, access rights should make every class or member as inaccessible as possible .

If the method of the subclass overrides the method of the parent class , Then the access level of the method in a subclass is not allowed to be lower than that of the parent class . This is to ensure that where parent instances can be used, subclass instances can be used instead of , That is to make sure that the Richter substitution principle is met .

Fields must never be public , Because by doing so you lose control of the behavior of this field modification , The client can modify it at will . For example, in the following example ,AccessExample Have id Public field , If at some point , We want to use int Storage id Field , Then you need to modify all the client code .

public class AccessExample {
public String id;
}

You can use public getter and setter Method to replace the public field , This allows you to control the behavior of the field changes .

public class AccessExample {
private int id;
public String getId() {
return id + "";
}
public void setId(String id) {
this.id = Integer.valueOf(id);
}
}

But there are exceptions , If it is a package-level private class or a private nested class , Then direct exposure of members won't have a particularly big impact .

public class AccessWithInnerClassExample {
private class InnerClass {
int x;
}
private InnerClass innerClass;
public AccessWithInnerClassExample() {
innerClass = new InnerClass();
}
public int getValue() {
return innerClass.x; // Direct access 
}
}

Abstract classes and interfaces

1. abstract class

Both abstract classes and abstract methods are used abstract Keyword to declare . If a class contains abstract methods , Then the class must be declared abstract .

The biggest difference between an abstract class and a normal class is this , Abstract class cannot be instantiated , Can only be inherited .

public abstract class AbstractClassExample {
protected int x;
private int y;
public abstract void func1();
public void func2() {
System.out.println("func2");
}
}
public class AbstractExtendClassExample extends AbstractClassExample {
@Override
public void func1() {
System.out.println("func1");
}
}
// AbstractClassExample ac1 = new AbstractClassExample(); // 'AbstractClassExample' is abstract; cannot be instantiated
AbstractClassExample ac2 = new AbstractExtendClassExample();
ac2.func1();

2. Interface

Interface is an extension of abstract class , stay Java 8 Before , It can be viewed as a completely abstract class , That is, it cannot be implemented in any way .

from Java 8 Start , Interfaces can also have default method implementations , This is because interfaces that do not support default methods are too expensive to maintain . stay Java 8 Before , If an interface wants to add a new method , Modify all classes that implement the interface , Let them all implement the new method .

Member of the interface ( Field + Method ) The default is public Of , And is not allowed to be defined as private perhaps protected. from Java 9 Start , Allows methods to be defined as private, In this way, we can define some reusable code without exposing the method .

The fields of the interface are by default static and final Of .

public interface InterfaceExample {
void func1();
default void func2(){
System.out.println("func2");
}
int x = 123;
// int y; // Variable 'y' might not have been initialized
public int z = 0; // Modifier 'public' is redundant for interface fields
// private int k = 0; // Modifier 'private' not allowed here
// protected int l = 0; // Modifier 'protected' not allowed here
// private void fun3(); // Modifier 'private' not allowed here
}
public class InterfaceImplementExample implements InterfaceExample {
@Override
public void func1() {
System.out.println("func1");
}
}
// InterfaceExample ie1 = new InterfaceExample(); // 'InterfaceExample' is abstract; cannot be instantiated
InterfaceExample ie2 = new InterfaceImplementExample();
ie2.func1();
System.out.println(InterfaceExample.x);

3. Compare

  • From the perspective of design , Abstract classes provide one IS-A Relationship , We need to satisfy the principle of substitution , That is, the subclass object must be able to replace all the superclass objects . An interface is more like a LIKE-A Relationship , It just provides a way to implement the contract , Interfaces and classes that implement them are not required to have IS-A Relationship .
  • In terms of usage , A class can implement multiple interfaces , But cannot inherit multiple abstract classes .
  • The fields of the interface can only be static and final Type of , The fields of the abstract class have no such restriction .
  • The members of the interface can only be public Of , Members of abstract classes can have multiple access rights .

4. Used to choose

Use interface :

  • You need to have unrelated classes implement a method , For example, unrelated classes can be implemented Comparable Interface compareTo() Method ;
  • Multiple inheritance is required .

Using abstract classes :

  • Code needs to be Shared among several related classes .
  • You need to be able to control access to inherited members , Not all of them public.
  • You need to inherit non-static and non-constant fields .

In many cases , Interfaces take precedence over abstract classes . Because interfaces do not have strict class hierarchy requirements for abstract classes , You have the flexibility to add behavior to a class . And from Java 8 Start , Interfaces can also have a default method implementation , The cost of modifying the interface also becomes very low .

super

  • Access the constructor of the parent class : have access to super() Function accesses the constructor of the parent class , This delegates some initialization to the parent class . It should be noted that , The subclass must call the constructor of the parent class to complete the initialization , Generally, the default constructor of the parent class is called , If the subclass needs to call other constructors of the parent class , Then you can use it super() function .
  • Access the member of the parent class : If a subclass overrides a method of the parent class , By using super Keyword to refer to the method implementation of the parent class .
public class SuperExample {
protected int x;
protected int y;
public SuperExample(int x, int y) {
this.x = x;
this.y = y;
}
public void func() {
System.out.println("SuperExample.func()");
}
}
public class SuperExtendExample extends SuperExample {
private int z;
public SuperExtendExample(int x, int y, int z) {
super(x, y);
this.z = z;
}
@Override
public void func() {
super.func();
System.out.println("SuperExtendExample.func()");
}
}
SuperExample e = new SuperExtendExample(1, 2, 3);
e.func();
SuperExample.func()
SuperExtendExample.func()

Overrides and overloads

1. rewrite (Override)

It's in the inheritance system , A subclass that implements a method that is identical in method declaration to the parent class .

To satisfy the inside substitution principle , There are three limitations to rewriting :

  • A subclass method must have access greater than or equal to a superclass method ;
  • The return type of a subclass method must be the return type of a parent method or its child .
  • The exception type thrown by a subclass method must be the exception type thrown by the parent class or its subtype .

Use @Override annotation , You can ask the compiler to check if the above three constraints are met .

In the following example ,SubClass by SuperClass Subclasses of ,SubClass Rewrote SuperClass Of func() Method . among :

  • Subclass method access is public, Larger than the parent protected.
  • The return type of the subclass is ArrayList<Integer>, Is the return type of the parent class List<Integer> Subclasses of .
  • The exception type thrown by subclass is Exception, It's the parent class that throws the exception Throwable Subclasses of .
  • Subclass override methods use @Override annotation , This allows the compiler to automatically check if the constraints are met .
class SuperClass {
protected List<Integer> func() throws Throwable {
return new ArrayList<>();
}
}
class SubClass extends SuperClass {
@Override
public ArrayList<Integer> func() throws Exception {
return new ArrayList<>();
}
}

When calling a method , First from this class to find out whether there is a corresponding method , If you don't go to the parent class again , See if it is inherited from the parent class . Otherwise, we need to transform the parameters , After converting to a parent class, see if there is a corresponding method . in general , The priority of the method call is :

  • this.func(this)
  • super.func(this)
  • this.func(super)
  • super.func(super)
/*
A
|
B
|
C
|
D
*/
class A {
public void show(A obj) {
System.out.println("A.show(A)");
}
public void show(C obj) {
System.out.println("A.show(C)");
}
}
class B extends A {
@Override
public void show(A obj) {
System.out.println("B.show(A)");
}
}
class C extends B {
}
class D extends C {
}
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();
// stay A in show(A obj), Call directly 
a.show(a); // A.show(A)
// stay A Does not exist in the show(B obj), take B Transformed into its father A
a.show(b); // A.show(A)
// stay B From A inherited show(C obj), Call directly 
b.show(c); // A.show(C)
// stay B Does not exist in the show(D obj), But existence comes from A inherited show(C obj), take D Transformed into its father C
b.show(d); // A.show(C)
// The quote is still B object , therefore ba and b The result of the call is the same 
A ba = new B();
ba.show(c); // A.show(C)
ba.show(d); // A.show(C)
}

2. heavy load (Overload)

Exists in the same class , A method that has the same name as an existing method , But parameter types 、 Number 、 There is at least one difference in order .

It should be noted that , Different return values , Everything else being the same is not an overload .

class OverloadingExample {
public void show(int x) {
System.out.println(x);
}
public void show(int x, String y) {
System.out.println(x + " " + y);
}
}
public static void main(String[] args) {
OverloadingExample example = new OverloadingExample();
example.show(1);
example.show(1, "2");
}
版权声明
本文为[Write code to change Basin]所创,转载请带上原文链接,感谢
https://javamana.com/2021/02/20210223174446195x.html

  1. 开源办公开发平台丨Mysql5.7两套四节点主从结构环境搭建教程(二)
  2. 开源办公开发平台丨Mysql5.7两套四节点主从结构环境搭建教程(一)
  3. Open source office development platform mysql5.7 two sets of four node master-slave structure environment building tutorial (2)
  4. HTTP的“无状态”和REST的“状态转换”
  5. Open source office development platform mysql5.7 two sets of four node master-slave structure environment building tutorial (1)
  6. 【大数据哔哔集20210128】使用Hive计算环比和同比
  7. 【大数据哔哔集20210125】Kafka将逐步弃用对zookeeper的依赖
  8. 【大数据哔哔集20210124】有人问我Kafka Leader选举?我真没慌
  9. 【大数据哔哔集20210123】别问,问就是Kafka高可靠
  10. Spring 事务、异步和循环依赖有什么关系?
  11. Spring 动态代理时是如何解决循环依赖的?为什么要使用三级缓存?
  12. "Stateless" of HTTP and "state transition" of rest
  13. [big data bibiji 20210128] use hive to calculate month on month and year on year
  14. [big data bibiji 20210125] Kafka will gradually abandon its dependence on zookeeper
  15. [big data beeps 20210124] someone asked me about Kafka leader election? I'm not in a panic
  16. [big data bibiji 20210123] don't ask, ask is Kafka highly reliable
  17. jQuery Gantt Package 在Visual Studio中创建一个新的ASP.NET项目
  18. What is the relationship between spring transactions, asynchrony, and circular dependencies?
  19. How to solve circular dependency in spring dynamic proxy? Why use level 3 caching?
  20. Unicode码的二进制转换(Java)
  21. JAVA的函数式接口
  22. JAVA里的元祖类
  23. JQuery Gantt package to create a new ASP.NET project
  24. Binary conversion of Unicode code (Java)
  25. The functional interface of Java
  26. Yuanzu class in Java
  27. Java中的CPU占用高和内存占用高的问题排查
  28. HashMap连环问你能答出几道?
  29. IntelliJ IDEA 还能画思维导图,果然最强 IDE!
  30. java中的反射和代理
  31. Troubleshooting of high CPU and memory usage in Java
  32. How many questions can you answer?
  33. IntelliJ idea can also draw mind maps. It's really the strongest ide!
  34. Reflection and proxy in Java
  35. Java中的CPU占用高和内存占用高的问题排查
  36. Linux OOM(out of memory)
  37. mysql 自定义函数因参数名称报错
  38. Troubleshooting of high CPU and memory usage in Java
  39. Linux OOM(out of memory)
  40. MySQL user defined function error due to parameter name
  41. echarts-gl 3D 地图柱状图可视化GDP
  42. Visualization of histogram of ecarts GL 3D map
  43. 金三银四如何应对Redis面试,一文深入Redis实战实践!
  44. 阿里资深架构师定制金三银四面试整理出来的一份Java核心知识点.pdf
  45. 为什么Java开发工程师工资高,却很多人想转行?
  46. How to deal with the interview of redis!
  47. Ali senior architect customizes a Java core knowledge point sorted out in the interview of golden, silver and four.pdf
  48. Why do java development engineers have high salaries, but many people want to change careers?
  49. 用注解开发SpringMVC
  50. Developing spring MVC with annotations
  51. 编译redis报错/deps/hiredis/libhiredis.a解决
  52. Compile redis report error / DEPs / hirredis / libhirredis. A solution
  53. 用注解开发SpringMVC
  54. Developing spring MVC with annotations
  55. Spring学习笔记-01
  56. Centos安装和卸载docker
  57. Spring learning notes-01
  58. Installing and uninstalling docker in CentOS
  59. Java基础-异常
  60. Java基础-反射