如何使一个类中的方法可以从另一个类访问?

时间:2015-02-21 21:19:40

标签: function methods call eiffel

我是埃菲尔的初学者。我上了2节课。主要叫APPLICATION

class
    APPLICATION

inherit
    ARGUMENTS

create
    make

feature {NONE} -- Initialization

    make
            -- Run application.
        do
            print ("test")
        end    
end

另一个名为BLUE的课程:

class
    BLUE
create
    make

feature
    make
        local
            dead:BOOLEAN
            active:BOOLEAN
            number:BOOLEAN

        do
            io.putstring ("writetest")
        end

end

我想知道如何使BLUE类中的方法可以从APPLICATION类中访问和调用?

3 个答案:

答案 0 :(得分:1)

在课程APPLICATION中,您可以添加b类型的本地变量BLUE,然后调用make作为其创建过程:

make
    local
        b: BLUE
    do
        create b.make
    end

答案 1 :(得分:1)

通常,面向对象语言中的类之间存在两种关系,允许一个类访问另一个类的特性:

  1. 继承,
  2. 客户 - 供应商关系。
  3. 在第一种情况下,该类继承父级的所有功能,并可以将它们称为自己的:

    class APPLICATION
    
    inherit
        BLUE
            rename
                    -- Class `APPLICATION' has `make' as well,
                    -- so the inherited one has to be renamed to avoid a clash.
                make as make_blue
            end
    
    create
        make
    
    feature {NONE} -- Initialization
    
        make
                -- Run application.
            do
                    -- This prints "test".
                print ("test")
                    -- Call the inherited feature `{BLUE}.test'
                    -- renamed above into `make_blue'
                    -- that prints "writetest".
                make_blue
            end
    
    end
    

    在继承的情况下,对同一对象执行调用。

    在客户 - 供应商关系中,对另一个对象执行调用。在您的示例中,要调用的功能与创建过程一致,因此调用将成为正在创建的对象的创建指令的一部分:

    class APPLICATION
    
    create
        make
    
    feature {NONE} -- Initialization
    
        make
                -- Run application.
            local
                other: BLUE
            do
                    -- This prints "test".
                print ("test")
                    -- Create an object of type `BLUE'
                    -- calling its creation procedure `make'
                    -- that prints "writetest".
                create other.make
            end
    
    end
    

    关于何时使用一种方法而不是另一种方法的粗略近似如下。我们可以将继承视为“is-a”,将客户 - 供应商视为“has”关系。例如,苹果有颜色,但它不是颜色,因此客户 - 供应商关系更合适。另一方面,它是一种水果,所以继承关系更合适。在后一种情况下,apple类通过指定一些其他属性(如形状和种子位置)来细化水果类。但它无法改进颜色类。与您的示例相同:APPLICATION似乎不是BLUE的示例,因此客户 - 供应商关系似乎更合适。

答案 2 :(得分:1)

首先,在BLUE中你需要一个方法,你不应该在create方法中进行写作,这会使你编写程序变得更加困难。特别是随着程序变得更加复杂。所以我添加了write_message它不是创建方法。

class
    BLUE

feature
    write_message
        local
            dead:BOOLEAN
            active:BOOLEAN
            number:BOOLEAN
        do
            io.putstring ("writetest")
        end
end

现在,我们需要调用新方法

class
    APPLICATION   
inherit
    ARGUMENTS
create
    make

feature {NONE} -- Initialization

    make
            -- Run application.
        local
             blue: BLUE
        do
            print ("test")
            create blue
            blue.write_message
        end
end