Что такое instance в java
Перейти к содержимому

Что такое instance в java

  • автор:

Что такое Instance (инстансы) в Java?

Добрый день!
Недавно начал изучать Java (по урокам Hexlet), и столкнулся с таким вопросом:
«Что такое Instance в Java и для чего они вообще нужны»?
Как я понял, экземпляр класса в Java создаётся так:

1 2 3 4 5 6 7
class Main { public static void main(String. args) { Game game = new Game(); } }

Первое слово Game — это инстанс?
Почему нельзя написать так

game = new Game();

Просто до этого изучал php, там экземпляры классов примерно так объявлялись.
Пока из-за этой темы не могу перейти к следующим урокам, так там «эти» инстансы везде используются.
Объясните пожалуйста новичку

Лучшие ответы ( 3 )
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:

Что такое INSTANCE в программирований ?
Вот читаю книгу на английском, но не могу понять INSTANCE, что это значит в программирований ? .

Как узнать что это за инстансы SQL Server?
Не пойму к каким сервисам относятся эти инстансы (см. аттач). Можно это как-то узнать?

Что такое |= в java?
Уважаемые киберфорумцы, встретил такой код:// ставим флаг, чтобы уведомление пропало после нажатия.

553 / 361 / 206
Регистрация: 27.11.2014
Сообщений: 1,043

Лучший ответ

Сообщение было отмечено mininvit как решение

Решение

«Что такое Instance в Java и для чего они вообще нужны»?
Это экземпляры классов.

Есть примитивные типы (boolean, byte, char, short, int, long, float и double), которые не превратили в классы, потому что и без этого программы виснут и бьют рекорды по производительности.

Есть другие типы — классы.

Достаточно объявить переменную примитивного типа и значение может сразу хранится в этой переменной. Поэтому пишут:
int n;

Если нужна переменная типа конкретного класса, то она уже не может вместить в себя все допустимые свойства класса, т.к. в java она хранит некий указатель на область памяти, где хранятся все свойства конкретного экземпляра класса. Поэтому в начале объявляют такую переменную:
Box myBox;
а потом выделяют место в памяти и записывают некую ссылку на эту область в переменную:
myBox = new Box();

И да! java строго типизированный язык. Поэтому требуется указывать тип каждой создаваемой переменной.

Регистрация: 16.07.2016
Сообщений: 186

ture, То есть instance это что то вроде типа (как int, double) только не для переменной как «int n;» а для класса?
Его нужно каждый раз писать, когда объявляешь экземпляр класса?

553 / 361 / 206
Регистрация: 27.11.2014
Сообщений: 1,043

Лучший ответ

Сообщение было отмечено mininvit как решение

Решение

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

Для int это могут быть простые числа (например 10 или 11), а для переменной типа какого-то класса конкретным значением станет instance(экземпляр) этого класса (в котором уже есть свойства, которые можно менять).

Когда объявляется переменная типа класса:
Box myBox;
то instance еще не существует (и через переменную не возможно поменять свойств). Переменная просто «не связана со значением». Значение нужно создать:
myBox = new Box();

java — это упрощения языка с++, для широкого использования. Вам могут быть не ясны конструкции, потому что это фрагменты конструкций другого языка. Упрощение, за которым теряется суть происходящего.
Переменная типа класса в java — это сложный объект, единственная задача которого хранить внутри ссылку(адрес расположения) реального объекта (который создается отдельно командой new) и предоставлять к нему доступ. Если реальный объект еще не создан, то переменная не может хранить его ссылку и предоставить к нему доступ. С примитивными типами все проще, потому что они являются тем, что мы о них думаем — конкретные простые значения, представимые в виде двоичного кода.

What exactly is an instance in Java?

What is the difference between an object, instance, and reference? They say that they have to create an instance to their application? What does that mean?

170k 28 28 gold badges 168 168 silver badges 176 176 bronze badges
asked Feb 26, 2011 at 9:22
4,297 7 7 gold badges 22 22 silver badges 15 15 bronze badges
possible duplicate of Difference between object and instance
Aug 27, 2014 at 19:30

12 Answers 12

An object and an instance are the same thing.

Personally I prefer to use the word «instance» when referring to a specific object of a specific type, for example «an instance of type Foo». But when talking about objects in general I would say «objects» rather than «instances».

A reference either refers to a specific object or else it can be a null reference.

They say that they have to create an instance to their application. What does it mean?

They probably mean you have to write something like this:

Foo foo = new Foo(); 

If you are unsure what type you should instantiate you should contact the developers of the application and ask for a more complete example.

155 1 1 gold badge 1 1 silver badge 14 14 bronze badges
answered Feb 26, 2011 at 9:25
Mark Byers Mark Byers
815k 194 194 gold badges 1586 1586 silver badges 1453 1453 bronze badges

I can’t edit it because it is only one character. Please add a «y» to the quote in your answer. «The say that the[y] have to..»

Feb 9, 2016 at 11:15

«instance to an application» means nothing.

«object» and «instance» are the same thing. There is a «class» that defines structure, and instances of that class (obtained with new ClassName() ). For example there is the class Car , and there are instance with different properties like mileage, max speed, horse-power, brand, etc.

Reference is, in the Java context, a variable* — it is something pointing to an object/instance. For example, String s = null; — s is a reference, that currently references no instance, but can reference an instance of the String class.

*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method — pass-by-value.

The value of s is a reference. It’s very important to distinguish between variables and values, and objects and references.

answered Feb 26, 2011 at 9:25
589k 146 146 gold badges 1061 1061 silver badges 1141 1141 bronze badges

When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame .

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.
Note: The phrase «instantiating a class» means the same thing as «creating an object.» When you create an object, you are creating an «instance» of a class, therefore «instantiating» a class.

The types of the Java programming language are divided into two categories: primitive types and reference types.
The reference types are class types, interface types, and array types.
There is also a special null type.
An object is a dynamically created instance of a class type or a dynamically created array .
The values of a reference type are references to objects.

answered Feb 26, 2011 at 9:24
3,838 1 1 gold badge 25 25 silver badges 18 18 bronze badges
I don’t think that j is an object. It just stores reference to an object.
Feb 26, 2011 at 9:28

Note that j isn’t even a reference, either. It’s a variable. The value of j is a reference. It’s very important to distinguish between variables and values, and objects and references.

Feb 26, 2011 at 9:29
I said stores reference not is reference. Maybe I don’t express myself well, but thats what I meant.
Feb 26, 2011 at 9:37

@Jon I had said j is the object that is created of the type JFrame. By that I mean j is a variable of reference type which is a JFrame datatype.

Feb 26, 2011 at 9:56

If that’s what you meant, that’s what you should have said. Given that this question is about the details of terminology, it’s incredibly important to be precise.

Feb 26, 2011 at 16:18

I think that Object = Instance. Reference is a «link» to an Object.

Car c = new Car(); 

variable c stores a reference to an object of type Car.

answered Feb 26, 2011 at 9:25
759 4 4 silver badges 8 8 bronze badges

Computer c= new Computer() 

Here an object is created from the Computer class. A reference named c allows the programmer to access the object.

81.9k 23 23 gold badges 145 145 silver badges 270 270 bronze badges
answered Sep 24, 2012 at 15:26
61 1 1 silver badge 1 1 bronze badge

The main differnece is when you say ClassName obj = null; you are just creating an object for that class. It’s not an instance of that class.

This statement will just allot memory for the static meber variables, not for the normal member variables.

But when you say ClassName obj = new ClassName(); you are creating an instance of the class. This staement will allot memory all member variables.

answered May 17, 2012 at 5:35
237 3 3 silver badges 9 9 bronze badges

basically object and instance are the two words used interchangeably. A class is template for an object and an object is an instance of a class.

answered Jul 8, 2015 at 6:54
karunesh pal karunesh pal
41 1 1 bronze badge

«creating an instance of a class» how about, «you are taking a class and making a new variable of that class that WILL change depending on an input that changes»

Class in the library called Nacho

variable Libre to hold the «instance» that will change

Nacho Libre = new Nacho(Variable, Scanner Input, or whatever goes here, This is the place that accepts the changes then puts the value in «Libre» on the left side of the equals sign (you know «Nacho Libre = new Nacho(Scanner.in)» «Nacho Libre» is on the left of the = (that’s not tech talk, that’s my way of explaining it)

I think that is better than saying «instance of type» or «instance of class». Really the point is it just needs to be detailed out more. «instance of type or class» is not good enough for the beginner. wow, its like a tongue twister and your brain cannot focus on tongue twisters very well. that «instance» word is very annoying and the mere sound of it drives me nuts. it begs for more detail. it begs to be broken down better. I had to google what «instance» meant just to get my bearings straight. try saying «instance of class» to your grandma. yikes!

What is an Instance in Java?

JavaTpoint

Java is recognised for its ability to construct and manipulate objects in object-oriented programming. An object is an instance of a class, and in the Java programming language, instances are fundamental. In this post, we’ll examine what a Java instance is and how classes and objects connect to it.

A class is used as a blueprint or template for constructing objects in Java. It specifies the characteristics and actions that objects belonging to that class will exhibit. A specific occurrence or realisation of a class, on the other hand, is what we mean by an instance. It represents a distinct object in memory that adheres to the structure specified by its class and is generated using the new keyword.

Let’s use an analogy to comprehend the idea of an instance better. Consider a class as a home’s floor plan. The blueprint details the design, measurements, and characteristics that will be present in every house that is constructed using it. In this scenario, a real house built from that blueprint serves as an example. Although each house constructed from the blueprint is distinct and may have its own special features, they are all created according to the blueprint’s design.

The properties (variables) and behaviours (methods) that objects created from a class in Java will have are similarly defined by the class. Instances are the name for these things. Every instance has a unique state that describes the values of its characteristics at any given moment. Although an instance’s state may vary as the programme executes, it continues to exist independently of other instances of the same class.

In Java, there are specific procedures that must be taken before creating an instance. A variable of the class type is first declared and serves as a pointer to the instance. To allocate memory and initialise the instance, use the new keyword in conjunction with the class constructor. An instance’s initial state is configured by the constructor, a unique method found in classes, which is responsible for doing so.

Here’s an example that demonstrates the creation of an instance in Java:

InstanceExample.java

Output:

Starting the Toyota car.

Explanation:

In the above code, we have a Car class with two attributes (brand and color) and a startEngine() method. In the Main class, we create an instance of Car called myCar by invoking the constructor with the values «Toyota» and «Red». We then call the startEngine() method on myCar, which outputs «Starting the Toyota car. » to the console.

Instances in Java allow us to create multiple objects with different states and behaviors based on a single class. This is a powerful feature that promotes code reuse, modularity, and flexibility. By creating instances, we can model real-world entities, represent data structures, implement algorithms, and build complex systems.

  • Multiple Instances: We can create multiple instances of a class, each with its own unique state and behavior. Each instance operates independently of others, even if they belong to the same class.
  • Instance Variables: Instances have their own set of instance variables, also known as member variables or attributes. These variables hold specific values for each instance and can be accessed and modified within the instance’s methods.
  • Encapsulation: Instances facilitate encapsulation, one of the key principles of object-oriented programming. By encapsulating data within an instance, you can control access to the instance variables and ensure that they are manipulated in a controlled manner through defined methods.
  • Inheritance and Instances: In Java, instances also play a role in inheritance. When a class inherits from another class, it can create instances of both the derived class and the base class. This allows the derived class to inherit the attributes and behaviors of the base class while adding its own unique features.
  • Instance Methods: Along with instance variables, instances also have associated instance methods. These methods define the behavior of the instance and can access and manipulate the instance’s variables. Instance methods can be invoked on specific instances to perform operations related to that instance.
  • Passing Instances as Parameters: Instances can be passed as parameters to methods or constructors, allowing them to interact with other instances or perform operations that involve multiple instances. This enables collaboration and communication between different objects in a Java program.
  • Garbage Collection: Instances in Java are managed by the garbage collector. When an instance is no longer referenced by any variables or reachable from the program’s execution context, it becomes eligible for garbage collection. The garbage collector automatically reclaims the memory occupied by these unused instances.

The foundation of Java’s object-oriented programming is comprised of instances. They make our code modular, reusable, and simpler to maintain by enabling us to create, modify, and interact with objects. You may use Java’s object-oriented paradigm to construct reliable and adaptable applications by comprehending the idea of instances and how they relate to classes and objects.

In conclusion, a Java instance is a class’s actualization in concrete form. It symbolises a particular thing with a distinct state and behaviour. The new keyword and a class constructor are both used to generate instances. They make Java a flexible and object-oriented programming language by allowing us to build and manipulate objects.

Next Topic What is Retrieval Operation in ArrayList Java

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook twitter pinterest

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 Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Trending Technologies

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

Что такое instance в java

In these situations, an instance of the Instance may be injected:

@Inject Instance paymentProcessor;

Any combination of qualifiers may be specified at the injection point:

@Inject @PayBy(CHEQUE) Instance chequePaymentProcessor;

Or, the @Any qualifier may be used, allowing the application to specify qualifiers dynamically:

@Inject @Any Instance anyPaymentProcessor;

Finally, the @New qualifier may be used, allowing the application to obtain a @New qualified bean:

@Inject @New(ChequePaymentProcessor.class) Instance chequePaymentProcessor;

For an injected Instance:

  • the required type is the type parameter specified at the injection point, and
  • the required qualifiers are the qualifiers specified at the injection point.

The inherited Provider.get() method returns a contextual references for the unique bean that matches the required type and required qualifiers and is eligible for injection into the class into which the parent Instance was injected, or throws an UnsatisfiedResolutionException or AmbiguousResolutionException .

PaymentProcessor pp = chequePaymentProcessor.get();

The inherited Iterable.iterator() method returns an iterator over contextual references for beans that match the required type and required qualifiers and are eligible for injection into the class into which the parent Instance was injected.

for (PaymentProcessor pp : anyPaymentProcessor) pp.test();

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type Method and Description
void destroy (T instance)

On destroy(Object) being called, the container destroys the instance if the active context object for the scope type of the bean supports destroying bean instances.

Determines if there is more than one bean that matches the required type and qualifiers and is eligible for injection into the class into which the parent Instance was injected.

Determines if there is no bean that matches the required type and qualifiers and is eligible for injection into the class into which the parent Instance was injected.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *