Как создавать объекты
— Так. С классами мы разобрались в прошлый раз. Сегодня я хочу рассказать тебе, как создавать объекты. Это очень просто: пишем ключевое слово new и имя класса, объект которого хотим создать:
Reader reader = new BufferedReader(new InputStreamReader(System.in));
InputStream is = new FileInputStream(path);
— Я знаю, поэтому слушай дальше.
— При создании объекта в скобочках можно передавать различные параметры. Об этом я расскажу сегодня, но чуть попозже. Давай рассмотрим класс Cat:
class Cat < public String name;
public String getName() < return name; > public void setName(String name) < this.name = name; > >
— А это что еще за геттеры и сеттеры такие?
— В Java принято скрывать переменные от доступа из других классов. Обычно переменные, объявленные внутри классов, имеют модификатор private.
— Чтобы другие классы могли менять значения таких переменных, для каждой из них создается пара методов: get и set. Задача метода get вернуть текущее значение переменной тому, кто его вызвал. Задача метода set установить новое значение переменной.
— Если мы не хотим, чтобы кто-то менял значения переменных наших объектов, мы можем просто не писать метод set для него, или сделать его private . Также в этот метод можно добавить дополнительные проверки данных. И если переданное новое значение неверно, то ничего не менять.
— Т.к. переменных в классе может быть много, то методы get и set обычно имеют в своем имени имя той переменной, с которой работают.
— Если переменная называется name, то методы setName и getName . И т.д. по аналогии.
— Ясно. Понятный, в общем-то, подход.
— Вот тебе еще пара примеров работы с новосозданным объектом:
catVaska.name = "Vaska"; catVaska.age = 6; catVaska.weight = 4;
Set and Get the Name of Thread in Java
In this article, we will learn to set and get thread names in Java with simple examples using the built-in methods setName() and getName() in the Thread class.
By default, the Java compiler sets a default name of each thread while creating, and we can get the thread name by using the Thread.currentThread().getName() method.
In the following example, we created a Thread by implementing the Runnable interface and its run() method. This code will print the default name of the thread to the console.
Thread thread = new Thread(() -> < System.out.println(Thread.currentThread().getName()); >); thread.start(); //Prints Thread-0
If we create more threads then the number part in the default name will increment with the number of threads i.e. Thread-1, Thread-2, Thread-3... etc.
Similarly, default names are generated for threads running in the ExecutorService in the pattern of pool-1-thread-1.
ExecutorService executorService = Executors.newFixedThreadPool(3); executorService.submit(() -> < System.out.println(Thread.currentThread().getName()); //Prints pool-1-thread-1 >);
If we run 3 tasks in this executor then the thread names will be pool-1-thread-1, pool-1-thread-2, pool-1-thread-3. Check out the following example to better understand the naming pattern.
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main < public static void main(String[] args) < ExecutorService executorService = null; try < executorService = Executors.newFixedThreadPool(3); //pool-1 executorService.submit(() ->< System.out.println(Thread.currentThread().getName()); //thread-1 >); executorService.submit(() -> < System.out.println(Thread.currentThread().getName()); //thread-2 >); executorService = Executors.newFixedThreadPool(3); //pool-2 executorService.submit(() -> < System.out.println(Thread.currentThread().getName()); //thread-1 >); > finally < executorService.shutdown(); >> >
pool-1-thread-1 pool-1-thread-2 pool-2-thread-1
We can set a custom name of the thread in two ways:
2.1. Using Thread Constructor
We can use one of the following constructors that accept the thread name as a parameter.
Thread(String name); Thread(Runnable task, String name); Thread(ThreadGroup group, String name); Thread(ThreadGroup group, Runnable task, String name);
Let us see an example of using a constructor to set the name of a thread.
Thread thread = new Thread(() -> < System.out.println("Thread name is : " + Thread.currentThread().getName()); //Prints "Thread name is : Demo-Thread" >, "Demo-Thread"); thread.start();
The setName() method takes a single string type argument and does not return anything. This method is helpful if we have not set the thread name during thread creation or threads are created using the lambda style syntax.
Thread thread= new Thread(() -> < System.out.println(Thread.currentThread().getName()); //Prints 'Custom-Thread' >); oddThread.setName("Custom-Thread");
Similarly, we can use this method with ExecutorSerivce as well.
This tutorial taught us different ways to set a new custom name for a thread. We used the thread class constructor and setName() method of the same class. Similarly, we used the getName() to get the thread name and understood the default names of threads given by JVM.
Setname method in java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
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
Setname method in java
Как вы заметили, 2-й элемент массива scores изменяется вне сеттера (в строке 5). Поскольку геттер возвращает ссылку на scores, внешний код, имея эту ссылку, может вносить изменения в массив.
Решение этой проблемы заключается в том, что геттеру необходимо возвращать копию объекта, а не ссылку на оригинал. Модифицируем вышеупомянутый геттер следующим образом:
Переменные примитивных типов вы можете свободно передавать/возвращать прямо в сеттере/геттере, потому что Java автоматически копирует их значения. Таким образом, ошибок № 2 и № 3 можно избежать.
private float amount; public void setAmount(float amount) < this.amount = amount; >public float getAmount()
String — это immutable-тип. Это означает, что после создания объекта этого типа, его значение нельзя изменить. Любые изменения будут приводить к созданию нового объекта String. Таким образом, как и для примитивных типов, вы можете безопасно реализовать геттер и сеттер для переменной String:
private String address; public void setAddress(String address) < this.address = address; >public String getAddress()
Т.к. объекты класса java.util.Date являются изменяемыми, то внешние классы не должны иметь доступ к их оригиналам. Данный класс реализует метод clone() из класса Object, который возвращает копию объекта, но использовать его для этих целей не стоит.
По этому поводу Джошуа Блох пишет следующее: «Поскольку Date не является окончательным классом, нет гарантии, что метод clone() возвратит объект, класс которого именно java.util.Date: он может вернуть экземпляр ненадежного подкласса, созданного специально для нанесения ущерба. Такой подкласс может, например, записывать ссылку на каждый экземпляр в момент создания последнего в закрытый статический список, а затем предоставить злоумышленнику доступ к этому списку. В результате злоумышленник получит полный контроль над всеми экземплярами копий. Чтобы предотвратить атаки такого рода, не используйте метод clone() для создания копии параметра, тип которого позволяет ненадежным сторонам создавать подклассы».