Переопределение static метода java

Переопределение методов

Если в иерархии классов совпадают имена и сигнатуры типов методов из подкласса и супер класса, то говорят, что метод из подкласса переопределяет метод из супер-класса.

Переопределение методов выполняется только в том случае, если имена и сигнатуры типов обоих методов одинаковы. В противном случае оба методы считаются перегружаемыми.

В следующем примере в классе M определен метод print() . В его наследнике классе N тоже определен метод print() с такой же сигнатурой, но другим поведением. Это и называется переопределением методов:

public class M < public int i; public int j; public M(int i, int j) < this.i = i; this.j = j; >public void print() < System.out.println("Метод M i = " + i + " j language-java">public class N extends M < public int k; public N(int i, int j, int k) < super(i, j); this.k = k; >public void print() < System.out.println("Метод N k language-java">public class OverrideDemo < public static void main(String[] args) < M obj1 = new M(7, 8); obj1.print(); N obj2 = new N(4, 5, 6); obj2.print(); M obj3 = new N(1, 2, 3); obj3.print(); >>
Метод M i = 7 j = 8 Метод N k = 6 Метод N k = 3

Существует такое понятие в Java как динамическая диспетчеризация методов - это механизм, с помощью которого вызов переопределенного метода разрешается во время выполнения, а не компиляции.

Переопределение методов это одна из форм реализации полиморфизма. Переопределение метода позволяет определить в общем классе методы, которые станут общими для всех производных от него классов, а в подклассах - конкретные реализации некоторых или всех этих методов.

Рассмотрим более конкретный пример, который показывает зачем переопределяются методы.

Создадим класс Figure , описывающий какую-то абстрактную фигуру и классы наследники Triangle и Rectangle . Класс Figure содержит метод calculateArea() , подсчитывающий площадь фигуры. У каждой фигуры своя формула для подсчета площади, поэтому в классах Triangle и Rectangle метод calculateArea() переопределяется соответствующим образом:

public class Figure < double dimension1; double dimension2; public Figure(double dimension1, double dimension2) < this.dimension1 = dimension1; this.dimension2 = dimension2; >public double calculateArea() < System.out.println("Площадь фигуры не определена."); return 0; >>
public class Rectangle extends Figure < public Rectangle(double dimension1, double dimension2) < super(dimension1, dimension2); >public double calculateArea() < System.out.println("B области четырехугольника."); return dimension1 * dimension2; >>
public class Triangle extends Figure < public Triangle(double dimension1, double dimension2) < super(dimension1, dimension2); >public double calculateArea() < System.out.println("B области треугольника."); return dimension1 * dimension2 / 2; >>

Создадим массив типа Figure , который будет содержать объекты типа Figure , Triangle и Rectangle . Подсчитаем площадь для каждого элемента перебирая элементы массива и вызывая метод calculateArea() для каждого элемента. Нам все равно какого типа объект - у каждого есть вызываемый метод calculateArea() . JVM с помощью динамической диспетчеризации выбирает нужный вариант метода, основываясь на реальном типе объекта:

Результат выполнения кода:

Площадь фигуры не определена. 0.0 B области четырехугольника. 100.0 B области треугольника. 50.0

2. Методы подставки

После выхода Java 5 появилась возможность при переопределении методов указывать другой тип возвращаемого значения, в качестве которого можно использовать только типы, находящиеся ниже в иерархии наследования, чем исходный тип. Такие типы еще называются ковариантными.

Например, класс S наследует класс R и переопределяет метод getInstance() . При переопределении возвращаемый тип метода может или остаться таким же - Box6 , или быть изменен на любого наследника класса Box6 - HeavyBox , ColorBox или Shipment :

3. Переопределение и статические методы

Статические методы не могут быть переопределены. Класс наследник может объявлять метод с такой же сигнатурой, что и супер класс, но это не будет переопределением. При вызове переопределенного метода JVM выбирает нужный вариант основываясь на типе объекта. Вызов же статического метода происходит без объекта. Версия вызываемого статического метода всегда определяется на этапе компиляции.

При использовании ссылки для доступа к статическому члену компилятор при выборе метода учитывает тип ссылки, а не тип объекта, ей присвоенного.

Создадим в супер классе и наследнике статические методы с одинаковой сигнатурой:

public class Sub extends Base < public static void go() < System.out.println("метод из Sub"); >>

Попробуем вызвать статический метод используя переменную типа Base , которая указывает на объект типа Sub . При вызове статического метода JVM найдет тип переменной и вызовет метод того же класса:

метод из Base метод из Sub

4. Переопределение методов в классах наследниках

Методы объявленные как private никто, кроме самого класса не видит. Поэтому их наличие/отсутствие никак не отражается на классах наследниках. Они с легкостью могут объявлять методы с такой же сигнатурой и любыми модификаторами. Но это плохой тон! Также класс наследник может расширить видимость protected метода до public . Сузить видимость класс наследник не может.

5. Аннотация @Override

Необязательная аннотация @Override используется с методом для указания того, что он переопределен. Если метод переопределен неверно, код не будет компилироваться:

  • Процедурное и объектно-ориентированное программирование
  • Принципы ООП
  • Классы и объекты
  • Конструктор
  • Ключевое слово this
  • Перегрузка
  • Стек и куча
  • Передача объектов в методы
  • Java varargs
  • Рекурсия
  • Сборщик мусора и метод finalize
  • Наследование
  • Ключевое слово super
  • Модификаторы доступа
  • Геттеры и сеттеры
  • Абстрактные классы и методы
  • Ключевое слово final
  • Задания

Источник

Overriding and Hiding Methods

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error. For more information on @Override , see Annotations .

Static Methods

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method has important implications:

  • The version of the overridden instance method that gets invoked is the one in the subclass.
  • The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

Consider an example that contains two classes. The first is Animal , which contains one instance method and one static method:

public class Animal < public static void testClassMethod() < System.out.println("The static method in Animal"); >public void testInstanceMethod() < System.out.println("The instance method in Animal"); >>

The second class, a subclass of Animal , is called Cat :

public class Cat extends Animal < public static void testClassMethod() < System.out.println("The static method in Cat"); >public void testInstanceMethod() < System.out.println("The instance method in Cat"); >public static void main(String[] args) < Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); >>

The Cat class overrides the instance method in Animal and hides the static method in Animal . The main method in this class creates an instance of Cat and invokes testClassMethod() on the class and testInstanceMethod() on the instance.

The output from this program is as follows:

The static method in Animal The instance method in Cat

As promised, the version of the hidden static method that gets invoked is the one in the superclass, and the version of the overridden instance method that gets invoked is the one in the subclass.

Interface Methods

Default methods and abstract methods in interfaces are inherited like instance methods. However, when the supertypes of a class or interface provide multiple default methods with the same signature, the Java compiler follows inheritance rules to resolve the name conflict. These rules are driven by the following two principles:

    Instance methods are preferred over interface default methods. Consider the following classes and interfaces:

public interface Mythical < default public String identifyMyself() < return "I am a mythical creature."; >>
public class Pegasus extends Horse implements Flyer, Mythical < public static void main(String. args) < Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); >>
public interface EggLayer extends Animal < default public String identifyMyself() < return "I am able to lay eggs."; >>

public interface FireBreather extends Animal

public class Dragon implements EggLayer, FireBreather < public static void main (String. args) < Dragon myApp = new Dragon(); System.out.println(myApp.identifyMyself()); >>

If two or more independently defined default methods conflict, or a default method conflicts with an abstract method, then the Java compiler produces a compiler error. You must explicitly override the supertype methods.

Consider the example about computer-controlled cars that can now fly. You have two interfaces ( OperateCar and FlyCar ) that provide default implementations for the same method, ( startEngine ):

public interface OperateCar < // . default public int startEngine(EncryptedKey key) < // Implementation >>

A class that implements both OperateCar and FlyCar must override the method startEngine . You could invoke any of the of the default implementations with the super keyword.

public class FlyingCar implements OperateCar, FlyCar < // . public int startEngine(EncryptedKey key) < FlyCar.super.startEngine(key); OperateCar.super.startEngine(key); >>

The name preceding super (in this example, FlyCar or OperateCar ) must refer to a direct superinterface that defines or inherits a default for the invoked method. This form of method invocation is not restricted to differentiating between multiple implemented interfaces that contain default methods with the same signature. You can use the super keyword to invoke a default method in both classes and interfaces.

Inherited instance methods from classes can override abstract interface methods. Consider the following interfaces and classes:

public class Mustang extends Horse implements Mammal < public static void main(String. args) < Mustang myApp = new Mustang(); System.out.println(myApp.identifyMyself()); >>

The method Mustang.identifyMyself returns the string I am a horse. The class Mustang inherits the method identifyMyself from the class Horse , which overrides the abstract method of the same name in the interface Mammal .

Note: Static methods in interfaces are never inherited.

Modifiers

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

You will get a compile-time error if you attempt to change an instance method in the superclass to a static method in the subclass, and vice versa.

Summary

The following table summarizes what happens when you define a method with the same signature as a method in a superclass.

Defining a Method with the Same Signature as a Superclass's Method

Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.

Источник

Переопределение static метода java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Читайте также:  Работа с jQuery
Оцените статью