Метод instance of java

Java instanceof Operator

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not.

objectName instanceOf className;

Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

Example: Java instanceof

name is an instance of String: true obj is an instance of Main: true

In the above example, we have created a variable name of the String type and an object obj of the Main class.

Here, we have used the instanceof operator to check whether name and obj are instances of the String and Main class respectively. And, the operator returns true in both cases.

Note: In Java, String is a class rather than a primitive data type. To learn more, visit Java String.

Java instanceof during Inheritance

We can use the instanceof operator to check if objects of the subclass is also an instance of the superclass. For example,

// Java Program to check if an object of the subclass // is also an instance of the superclass // superclass class Animal < >// subclass class Dog extends Animal < >class Main < public static void main(String[] args) < // create an object of the subclass Dog d1 = new Dog(); // checks if d1 is an instance of the subclass System.out.println(d1 instanceof Dog); // prints true // checks if d1 is an instance of the superclass System.out.println(d1 instanceof Animal); // prints true >>

In the above example, we have created a subclass Dog that inherits from the superclass Animal . We have created an object d1 of the Dog class.

Читайте также:  Unicode objects must be encoded before hashing python

Inside the print statement, notice the expression,

Here, we are using the instanceof operator to check whether d1 is also an instance of the superclass Animal .

Java instanceof in Interface

The instanceof operator is also used to check whether an object of a class is also an instance of the interface implemented by the class. For example,

// Java program to check if an object of a class is also // an instance of the interface implemented by the class interface Animal < >class Dog implements Animal < >class Main < public static void main(String[] args) < // create an object of the Dog class Dog d1 = new Dog(); // checks if the object of Dog // is also an instance of Animal System.out.println(d1 instanceof Animal); // returns true >>

In the above example, the Dog class implements the Animal interface. Inside the print statement, notice the expression,

Here, d1 is an instance of Dog class. The instanceof operator checks if d1 is also an instance of the interface Animal .

Note: In Java, all the classes are inherited from the Object class. So, instances of all the classes are also an instance of the Object class.

In the previous example, if we check,

Источник

Что такое ключевое слово instanceof в Java?

Java instanceof — это ключевое слово. Это двоичный оператор, используемый для проверки, является ли объект (экземпляр) подтипом данного типа. Он возвращает либо true, либо false. Он возвращает true, если левая часть выражения является экземпляром имени класса с правой стороны. Instanceof оценивает значение true, если объект принадлежит определенному классу или его суперклассу; else вызывает ошибку компиляции. Если мы применим оператор instanceof с любой переменной с нулевым значением, он вернет false. Это полезно, когда ваша программа может получить информацию о типе времени выполнения для объекта. Ключевое слово instanceof также известно как оператор сравнения типов, поскольку он сравнивает экземпляр с типом.

Синтаксис

( Object reference variable ) instanceof (class/interface type)

Пример

interface Vehicle <> class Car <> class Ford extends Car implements Vehicle <> class Suzuki extends Car implements Vehicle <> public class TestClass < public static void main(String[] args) < Object ford = new Ford(); if ( ford instanceof Vehicle ) < System.out.println("True: Ford implements Vehicle"); >if ( ford instanceof Car ) < System.out.println("True: Ford extends Car"); >if ( ford instanceof Ford ) < System.out.println("True: Ford is Ford"); >if ( ford instanceof Object ) < System.out.println("True: Object is the parent type of all objects"); >> >

Однако, с Object car = new Car();

if ( car instanceof Ford ) // fasle

В приведенном выше случае он возвращает фальсификацию, потому что автомобиль является супертипом Ford и, возможно, менее «усовершенствованным».

Кроме того, если попробовать ford instanceof Suzuki даже не компилировать! Это потому, что Ford не является подтипом или супертипом Suzuki, и он также не реализует его.

Важно отметить, что переменная, используемая для ford выше, имеет тип Object. Это означает, что instanceof является операцией во время выполнения и приводит нас к прецеденту: реагировать по-разному на основе типа объекта во время выполнения.

В некоторых других случаях ключевое слово instanceof — полезный инструмент, когда у вас есть коллекция объектов, и вы не знаете, что это такое. Например, у вас есть коллекция элементов управления в форме. Вы хотите прочитать проверенное состояние всех флажков, но вы не можете запросить простой старый объект для его проверенного состояния. Вместо этого вы увидите, является ли каждый объект флажком, и если да, установите его в поле и проверьте его свойства.

if (obj instanceof Checkbox)

ключевое слово instanceof и значение null

Если мы применим оператор instanceof с переменной с нулевым значением, она вернет false. Давайте посмотрим пример, приведенный ниже, где мы применяем оператор instanceof с переменной, имеющей нулевое значение.

Источник

Применение оператора instanceof в Java

Применение оператора instanceof в Java

Иногда тип объекта полезно выяснить во время выполнения. Например, в од­ном потоке исполнения объекты разных типов моrут формироваться, а в другом потоке исполнения — использоваться.

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

В Java неправильное приведение типов влечет за собой появление ошибки во время выполнения.

Большинство ошибок приведения типов может быть выявлено на стадии компиляции. Но приведение типов в пределах иерархии классов может стать причиной ошибок, которые обнаруживаются только во вре­мя выполнения.

Например, суперкласс А может порождать два подкласса: В и С. Следовательно, приведение объекта класса В или С к типу А вполне допустимо, но приведение объекта класса В к типу С ( и наоборот) — неверно. А поскольку объект типа А может ссылаться на объекты типа В и С, то как во время выполнения узнать, на какой именно тип делается ссылка перед тем, как выполнить приведение к типус? Это может быть объект типа А, В или С.

Чтобы заказать ретвиты на посты в Твиттере или лайки к ним же, переходите по предложенной ссылке на надежный сервис SMM. Тут Вы сможете получить высококачественное исполнение услуги, а также максимально возможные оптовые скидки на данный ресурс.

Если это объект типа В, то во время вы­полнения будет сгенерировано исключение. Для разрешения этого вопроса в Java предоставляется оператор времени выполнения instanceof, который имеет сле­дующую общую форму:

Источник

Java — Difference between getClass() and instanceof in equals() method?

You might have seen both getClass() , and instanceof operator in Java can be used in the equals() method to verify the type of the object you are checking for equality. Do you know what the difference is between using getClass() vs instanceof operator in Java? What would be the consequence of using one over the other in the equals() method? This is one of the tricky Java interview questions, which some of you might have encountered. There is a very subtle difference between getClass() and instanceof operator, which can cause potential issues with respect to the equals() method.

Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.

This can break the symmetry clause of the equals() method but can also be leveraged for flexibility and performance as Hibernate does by using proxies in place of actual classes. Let’s see some code examples to understand this difference better.

Difference between instanceof vs getClass() in Java

Before jumping into the equals() method and how they break the symmetry clause let’s verify the behavior getClass() and instanceof operator in Java. Consider the below code, what do you think it will return, true or false?

boolean result = (loader.getClass() == Thread.class); // true result = (loader.getClass() == Runnable.class); // false because we are testing against Runnable result = loader instanceof Thread; // true because the loader is an object of Thread class result = loader instanceof Runnable; // true because the loader is an instance of Thread // and it implements Runnable

So, you can see that getClass() put a restriction that objects are only equal to other objects of the same class, the same runtime type, but instanceof operator returns true for subclass as well.

If you use the getClass() in the equals() method then it will only return true if the other object is also of the same class or same runtime type, it will return false even if its object of subclass and follow the Liskov substitution principle.

Due to this restriction, many Java developers including the great Joshua Bloch have recommended using the instanceof operator in equals() method.

Java - Difference between getClass() and instanceof in equals() method?

The instanceof operator lets you implement equality between super class and sub class. This is very important from the Collections framework perspective which uses the equals() method to find values. If you use the instanceof operator in equals() method then you can retrieve values even with the object of the subclass as a key provided they have the same content, but this is not possible when you use the getClass() method.

Hibernate relies for its performance gain on this behavior of instanceof operator. If you remember, there is a restriction in place for any Entity or Persistence class in Hibernate that it cannot be final.

This is because hibernate internally creates Proxy classes by extending your Entity class and use it until you really need an attribute from the database. Since instanceof is used to verify the type of object, a Proxy can be equal to the original object.

On the other hand, using instanceof operator has one disadvantage as well. It doesn’t respect the symmetry contract of equals() method. The symmetry property says that if x.equals(y) is true then y.equals(x) should also be true, but if you swap x with subclass then x instanceof y would be true but y instanceof x will be false, hence equals() method will return false.

This is the fact you should consider when deciding whether to use getClass() or instanceof operator for overriding equals() in Java.

That’s all on the difference between getClass() and instanceof in Java. Just remember that getClass() return false if you compare it with the instanceof the subclass but the instance of operator trues if the object is a subclass of the class on the right-hand side of the operator.

The biggest disadvantage of using getClass() in the equals() method is the fact that you get two objects that appear to be equal (because they are equal on all the fields) but they are not equal because they are of different classes.

This can cause surprising behavior hence Joshua Bloch and others recommend using the instanceof operator inside equals() method in Java.

Источник

Оцените статью