#30 Перегрузка методов класса в Паскале. ООП
Primary tabs
Перегрузка методов
Перегрука метода - возможность определить несколько методов с одинаковыми именами, но различными сигнатурами внутри одного и того же класса.
Рассмотрим примеры.
Пример №1 - перегрузка по количеству параметров
type
Human = class // родительский класс
public
procedure sayHello();
procedure sayHello(name: string);
procedure sayHello(name, surname: string);
end;
procedure Human.sayHello();
begin
writeln('Привет, я человек!');
end;
procedure Human.sayHello(name: string);
begin
writeln('Привет, я ' + name + '!');
end;
procedure Human.sayHello(name, surname: string);
begin
writeln('Привет, я ', name, ' ', surname, '!');
end;
var
Man: Human;
begin
Man := Human.create();
Man.sayHello();
Man.sayHello('Вася');
Man.sayHello('Вася', 'Петров');
end.
-- объект класса Human тут умеет здоровать тремя различными способами, все зависит от количества переданных параметров.
Перегружать методы можно не только по количеству параметров, но и по их типам.
Пример №2 - перегрузка и переопределение
Перегруженные методы можно переопределять (как и обычные неперегругруженные):
type
Human = class // родительский класс
public
procedure sayHello();
procedure sayHello(name: string);
procedure sayHello(name, surname: string);
end;
ModernHuman = class(Human)
procedure sayHello();
procedure sayHello(name: string);
end;
procedure Human.sayHello();
begin
writeln('Привет, я человек!');
end;
procedure Human.sayHello(name: string);
begin
writeln('Привет, я ' + name + '!');
end;
procedure Human.sayHello(name, surname: string);
begin
writeln('Привет, я ', name, ' ', surname, '!');
end;
procedure ModernHuman.sayHello(name: string);
begin
writeln('Привет, я житель XXI века ' + name + '!');
end;
procedure ModernHuman.sayHello();
begin
writeln('Привет, я житель XXI века!');
end;
var
Man: Human;
NewMan: ModernHuman;
begin
Man := Human.create();
Man.sayHello();
Man.sayHello('Вася');
Man.sayHello('Вася', 'Петров');
NewMan := ModernHuman.create();
NewMan.sayHello();
NewMan.sayHello('Вася');
end.
Видео-материалы
- Перегрузка методов класса. Введение: https://youtu.be/oxLXUuWOAho
- Log in to post comments
- 1479 reads