`

Polymorphism classic example

    博客分类:
  • Java
 
阅读更多

The classic example in OOP is the “shape” example. This is commonly used because it is easy to visualize, but unfortunately it can confuse novice programmers into thinking that OOP is just for graphics programming, which is of course not the case.

 

The shape example has a base class called Shape and various derived types: Circle, Square, Triangle, etc. The reason the example works so well is that it’s easy to say “a circle is a type of shape” and be understood. The inheritance diagram shows the relationships:


The upcast could occur in a statement as simple as:
Shape s = new Circle();


Here, a Circle object is created, and the resulting reference is immediately assigned to a Shape, which would seem to be an error (assigning one type to another); and yet it’s fine because a Circle is a Shape by inheritance. So the compiler agrees with the statement and doesn’t issue an error message.

 

Suppose you call one of the base-class methods (that have been overridden in the derived classes):
s.draw();

 

Again, you might expect that Shape’s draw( ) is called because this is, after all, a Shape reference—so how could the compiler know to do anything else? And yet the proper Circle.draw( ) is called because of late binding (polymorphism).
The following example puts it a slightly different way. First, let’s create a reusable library of Shape types:

Shape.java

package org.fool.polymorphism;

public class Shape {
	public void draw() {
	}

	public void erase() {
	}
}

 Circle.java

package org.fool.polymorphism;

public class Circle extends Shape {

	@Override
	public void draw() {
		System.out.println("Circle.draw()");
	}

	@Override
	public void erase() {
		System.out.println("Circle.erase()");
	}

}

 Square.java

package org.fool.polymorphism;

public class Square extends Shape {

	@Override
	public void draw() {
		System.out.println("Square.draw()");
	}

	@Override
	public void erase() {
		System.out.println("Square.erase()");
	}

}

 Triangle.java

package org.fool.polymorphism;

public class Triangle extends Shape {

	@Override
	public void draw() {
		System.out.println("Triangle.draw()");
	}

	@Override
	public void erase() {
		System.out.println("Triangle.erase()");
	}

}

 PolymorphismTest.java

package org.fool.polymorphism;

import java.util.Random;

public class PolymorphismTest {

	public static class RandomShapeGenerator {
		private static Random rand = new Random(47);

		public static Shape next() {
			switch (rand.nextInt(3)) {
			default:
			case 0:
				return new Circle();
			case 1:
				return new Square();
			case 2:
				return new Triangle();
			}
		}
	}

	public static void main(String[] args) {
		Shape[] shapes = new Shape[9];

		// Fill up the array with shapes:
		for (int i = 0; i < shapes.length; i++) {
			shapes[i] = RandomShapeGenerator.next();
		}

		// Make polymorphic method calls:
		for (Shape s : shapes) {
			s.draw();
		}
	}
}

 

The base class Shape establishes the common interface to anything inherited from Shape—that is, all shapes can be drawn and erased. The derived classes override these definitions to provide unique behavior for each specific type of shape.

RandomShapeGenerator is a kind of “factory” that produces a reference to a randomly-selected Shape object each time you call its next( ) method. Note that the upcasting happens in the return statements, each of which takes a reference to a Circle, Square, or Triangle and sends it out of next( ) as the return type, Shape. So whenever you call next( ), you never get a chance to see what specific type it is, since you always get back a plain Shape reference.

main( ) contains an array of Shape references filled through calls to RandomShapeGenerator.next( ). At this point you know you have Shapes, but you don’t know anything more specific than that (and neither does the compiler). However, when you step through this array and call draw( ) for each one, the correct type-specific behavior magically occurs, as you can see from the output when you run the program.

The point of creating the shapes randomly is to drive home the understanding that the compiler can have no special knowledge that allows it to make the correct calls at compile time. All the calls to draw( ) must be made through dynamic binding.

 

  • 大小: 8 KB
分享到:
评论

相关推荐

    polymorphism&inheritance feature example in C++

    this is an example for polymorphism and inheritance feature of OOP C++. A reference for C++ starter.

    Polymorphism

    ### 多态性 (Polymorphism) #### 概述 多态性是面向对象编程中的一个核心概念,它允许在程序设计中定义多种类的方法来处理数据类型未知的对象。通过多态,我们可以创建灵活且可扩展的应用程序。本文将通过几个具体...

    《Polymorphism in C++ 》( 多型与虚拟).rar

    Polymorphism in C++ _ 多型与虚拟_.rar 候老力作 推荐 “在语法粗具的基础上,直接把读者导引到最核心最重要的思想,并且 在建立这个思想的过程中,提供足够的必要基础。 &lt;br&gt;”

    Java Program Design: Principles, Polymorphism, and Patterns

    The design of a simplified banking program is introduced in chapter 1 in a non-object-oriented incarnation and the example is carried through all chapters. You can see the object orientation develop ...

    code for understanding java polymorphism

    code for understanding java polymorphism,测试代码

    多型与虚拟Polymorphism in C++

    在C++编程语言中,多型(Polymorphism)是一个核心概念,它允许不同类型的对象对同一消息作出不同的响应,增强了代码的灵活性和重用性。多型在面向对象编程中扮演着至关重要的角色,主要体现在函数重载、运算符重载...

    Python库 | polymorphism-0.1.0-py3-none-any.whl

    `polymorphism-0.1.0-py3-none-any.whl` 是一个针对Python 3编写的库,名为"polymorphism",版本为0.1.0。这个库通常是一个已经打包好的可安装文件,它遵循Python的wheel格式,这是一种用于分发Python软件的二进制包...

    dnasp 5.1 DNA序列单核苷酸多态性分析综合软件,功能强大 software

    DnaSP DNA Sequence Polymorphism is a software package for the analysis of nucleotide polymorphism from aligned DNA sequence data DnaSP can estimate several measures of DNA sequence variation within ...

    Functional Programming with Overloading and Higher-Order Polymorphism PDF 英文

    ### 函数式编程中的过载与高阶多态性 #### 概述 本文档《函数式编程中的过载与高阶多态性》由马克·P·琼斯撰写,旨在探讨函数式编程语言中的一些高级特性,特别是针对Hindley/Milner类型系统的扩展。...

    Polymorphism.java

    该程序实现了三个类:抽象父类Student(包括了一些学生的基本信息,如姓名,所学课程,课程成绩等)和其子类Undergraduate,Postgraduate。两个子类之间的主要差别是计算课程成绩等级的标准有所不同。

    Single nucleotide polymorphism identification

    ### 单核苷酸多态性(Single Nucleotide Polymorphism, SNP)识别在肥胖候选基因系统中的应用 #### 摘要 本文主要介绍了单核苷酸多态性(SNP)在肥胖相关候选基因系统中的识别方法及其意义。通过对68个肥胖相关的...

    C++EXAMPLE

    此外,还有对象实例化、继承(inheritance)、多态(polymorphism)和封装(encapsulation)等概念。 3. **构造函数与析构函数**: 构造函数是类的一个特殊成员函数,用于在创建对象时初始化成员变量;析构函数则在...

    Abstract Class Polymorphism_C#_

    在C#编程语言中,抽象类(Abstract Class)和多态性(Polymorphism)是面向对象编程的核心概念。这两个概念对于任何C#初学者来说都至关重要,因为它们能够帮助开发者构建灵活、可扩展和易于维护的代码。 首先,我们...

    多态Polymorphism3---马克-to-win java视频

    多态 Polymorphism 马克-to-win java视频的详细介绍

    多态Polymorphism4---马克-to-win java视频

    多态Polymorphism 马克-to-win java视频的详细描述介绍

    多态Polymorphism5---马克-to-win java视频

    多态 Polymorphism 马克-to-win java视频的详细的介绍

    多态Polymorphism1---马克-to-win java视频

    多态 Polymorphism 马克-to-win java视频的详细描述介绍

    java-program-design-principles-polymorphism

    Get a grounding in polymorphism and other fundamental aspects of object-oriented program design and implementation, and learn a subset of design patterns that any practicing Java professional simply ...

    Accelerated C++ Practical Programming by Example

    13.2 Polymorphism and virtual functions 13.3 Using inheritance to solve our problem 13.4 A simple handle class 13.5 Using the handle class 13.6 Subtleties 13.7 Details Chapter 14 Managing memory ...

Global site tag (gtag.js) - Google Analytics