当前位置:网站首页>Shandong University project training raspberry pie promotion plan phase II (IX) inheritance and innovation
Shandong University project training raspberry pie promotion plan phase II (IX) inheritance and innovation
2022-04-22 21:13:00 【indaeyo】
Catalog
Experiment four Inheritance and polymorphism
Ideas and considerations of experimental design
Polymorphism and dynamic binding
Experiment four Inheritance and polymorphism
The experiment purpose
Master the concepts and implementation methods of inheritance and polymorphism .
Master how to derive subclasses from existing classes and inherit parent classes .
Master the coverage and overloading of methods .
Experimental content
Realization Student class 、Sort class , Meet the following requirements :
- Student Class includes student number sid、 The student's name name、 Student phone phone Three private data fields , And have its get Method .
- There are three ways to construct data fields .
- rewrite Student Class toString() Method , Make the output form “sid:201835132290, name:Hailey, phone=243-555-2837”.
- Student Inherit Comparable Achieve polymorphism , rewrite compareTo() Method ; To write Sort Class selectionSort(Comparable<T>[] list) Method , To achieve together Student Objects are sorted from small to large according to the student number .
- The test procedure gives student An array of objects , call selectionSort(Comparable<T>[] list) Method to sort it , Finally, the output of student information sorted by student number is obtained . Such as :
sid:201934562346,name:Sarah,phone=457-555-7862
sid:202012434629,name:Marsha,phone=587-555-1225
Ideas and considerations of experimental design
Parents and children
We can define new classes from existing classes , This is called class inheritance . The new class is called subclass 、 Subclasses and inheritance classes ; Existing classes are called superclasses 、 Parent or base class .
grammar :
public class Circle extends GeometricObject
extends Is an inherited keyword ,GeometricObject For the parent class Superclass, and Circle It's a subclass Subclass. By inheritance ,Circle Class owned GeometricObject Class You can visit Data fields and methods .
Private data fields in the parent class are inaccessible outside the class . therefore , You cannot directly use the of a parent class in a subclass private Data fields . however , If a public accessor or modifier is defined in the parent class , Then it can be accessed through these public accessors and modifiers / Modify them .
Super Use of keywords
Super Keyword refers to the surrogate parent class , It can be used to call ordinary methods and constructor methods in the parent class .
notes : The constructor of the parent class will not be inherited by the child class , They can only use keywords to call from the construction method of the subclass. .
such as :
public class GeometricObject {
public GeometricObject(){}
}
class Circle extends GeometricObject{
public Circle() {
super();// If the parent class has a parameter construction method , It can be used super(parameters)
}
}
Super When calling the normal method of the parent class , The grammar is different :super. Method name ( Parameters )
For example, the parent class has getDateCreated() Method ,Circle In a class printCircle() Method calls it :
public void printCircle(){
System.out.println("The circle is created"+super.getDateCreated()+"and the radius is"+ radius);
}
Method rewriting / Cover
That is, when a subclass inherits a method from its parent class , Sometimes you need to modify the implementation of the method defined in the parent class , Then you need to define the method in the subclass with the same signature and return value type as the parent class .
Here are two points to note :
- Only if the instance's method is accessible , It can be covered . Because a private method cannot be accessed outside its class itself , So it can't be covered .
- Just like the instance method , Static methods can also be inherited . however , Static methods cannot be overridden . If the static method defined in the parent class is redefined in the child class , Then the static methods defined in the parent class will be hidden . You can use grammar : Parent class name . Static method name , Call hidden static methods .
Method overloading
Overloading means defining multiple methods with the same name but different signatures .
Because overloading has been mentioned before , So here is an example to show the difference between rewriting and overloading .
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println("B:" + i);
}
}
class A extends B {
@Override
public void p(double i) {
System.out.println("A:" + i);
}
}

public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println("B:" + i);
}
}
class A extends B {
public void p(int i) {
System.out.println("A:" + i);
}
}

Run... In the first paragraph of the program Test Class time ,a.p(10) and a.p(10.0) All calls are defined in the class A Medium p(double i) Method , So the program shows 10.0. Run... In the second paragraph Test Class time ,a.p(10) Calling class A As defined in p(int i) Method , The display output is 10, and a.p(10.0) The call is defined in the class B Medium p(double i) Method , The display output is 10.0.
Polymorphism and dynamic binding
Polymorphism means that the variables of the parent class can point to the objects of the child class , It is often reflected in dynamic binding . Dynamic binding is that methods can be implemented in multiple classes along the inheritance chain ,JVM Decide which method to call at run time .
Examples are as follows :
public class DynamicBindingDemo {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Object x) {
System.out.println(x.toString());
}
}
class GraduateStudent extends Student {
}
class Student extends Person {
@Override
public String toString() {
return "Student";
}
}
class Person extends Object {
@Override
public String toString() {
return "Person";
}
}
Running results :

As can be seen from the example , class GraduateStudent、Student、Person、Object They all have their own right to toString() Method implementation , Which implementation to use depends on the runtime x Actual type .
Object Class equals Method
Like toString() Method ,equals(Object) The method is defined in Object Another useful method in class , It tests whether two objects are equal .
Its signature is :public boolean equals(Object obj)
The syntax for calling it is :object1.equals(object2)
Object The default implementation of this method in the class is :
public boolean equals(Object obj) {
return (this==obj);
}
This implementation uses == Operator to detect whether two reference variables point to the same object .
Experimental example code
public class Student implements Comparable<Student>{
private String sid;
private String name;
private String phone;
public String getSid() {
return sid;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public Student( String sid,String name, String phone) {
this.sid = sid;
this.name = name;
this.phone = phone;
}
@Override
public String toString() {
return "sid:"+sid+",name:"+name+",phone="+phone;
}
@Override
public int compareTo(Student o) {
int result=sid.compareTo(o.getSid());
return result;
}
}
class Sort<T>{
public void selectionSort(Comparable<T>[] list){
int min;
Comparable<T> temp;
for(int index=0;index<list.length-1;index++){
min=index;
for(int scan=index+1;scan<list.length;scan++){
if (list[scan].compareTo((T)list[min])<0){
min=scan;
}
}
temp=list[min];
list[min]=list[index];
list[index]=temp;
}
}
}
版权声明
本文为[indaeyo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221817586315.html
边栏推荐
- 反射与注解
- 毕业设计第8周学习记录
- Webmaster Tools - Webmaster software website - Webmaster Tools website - Webmaster essential tools free
- QTP11.5/UFT含中文汉化包
- Section de configuration des outils générée par le concepteur dans Visual Studio. Solution au problème de la mise à jour tardive des fichiers UI
- QT使用windeployqt.exe打包程序
- cuda10. 2. Install torch 1 nine
- QTP11使用教程
- R语言数据读取、清洗、一元线性回归
- 2022年R2移动式压力容器充装培训试题及在线模拟考试
猜你喜欢

Design and implementation of Snake game based on OpenGL

Win10安装Neo4j

Big talk test data (I)

Win10 installation neo4j

Hdlbits (XI) learning notes - finite state machine (FSM onehot - FSM serialdp)

Soochow securities x kangaroo cloud: the data is easily available and has millisecond response ability. What did Soochow securities do right?

nodejs笔记2

344-Leetcode 二叉树的所有路径

Botu PLC user defined data type
![[server data recovery] a data recovery case in which multiple hard disks are disconnected and the server crashes due to water ingress in the server](/img/e9/5a94aef710f0185a432a459f67fa75.jpg)
[server data recovery] a data recovery case in which multiple hard disks are disconnected and the server crashes due to water ingress in the server
随机推荐
SEREDS解串模块简介以及硬件实现
nodejs笔记3
(1) UART subsystem learning plan
HDLBits(十 一)学习笔记——有限状态机(FSM onehot - Fsm serialdp)
网传华为面试题:“800kg的牛如何过承重700kg的桥?”你怎样思考问题,就怎样过一生
JMeter data and software
机器视觉需要掌握的知识
2022-4-22 Leetcode 279.完全平方数
2022年危险化学品经营单位安全管理人员上岗证题库及模拟考试
【数据清洗、绘图】Dataframe的简易应用
Confidence interval and interval estimation
kubernetes_ How to solve the problem that namespace cannot be deleted
BLE---Advertisement data format & service
【MySQL从入门到精通】:关于常用like子句中通配符的总结
All paths of 344 leetcode binary tree
手写链表~内含单向链表和双向链表,请大家放心食用
QTP11使用教程
Leetcode-209-subarray with the smallest length
(一)UART子系统学习计划
Big talk test data (I)