Урок 18: Инкапсуляция. Сеттеры и геттеры. 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Урок 18: Инкапсуляция. Сеттеры и геттеры.



https:// www. youtube. com/ watch? v= zf3 lDojNxlA& list= PLAma_ mKffTOSUkXp26 rgdnC0 PicnmnDak& index=18 public class ClassesAndObjects {
public static void main(String[] args) {
   Person person1 = new Person ();
   person1.setName ("Roman");
   person1.setAge (50);

   person1.speak ();

   System. out. println ("person1.getName () - " + person1.getName ());
   System. out. println ("person1.getAge () - " + person1.getAge ());
}
}

class Person {
private String name;
private int age;

public void setName(String userName){
   name = userName;
}
public String getName(){
   return name;
}

public void setAge(int userAge){
   age = userAge;
}
public int getAge() {
   return age;
}

void speak() {
   System. out. println ("My name is " + name + ", and I am " + age + " years old.");
}
}

 

 

Вывод в консоль:

 

My name is Roman, and I am 50 years old.

person1.getName () - Roman

person1.getAge () - 50

 

 

Проверка введенных данных в классе Person.

 

public class ClassesAndObjects {
public static void main(String[] args) {
   Person person1 = new Person ();
   person1.setName ("");
   person1.setAge (-1);

   person1.speak ();

   System. out. println ("person1.getName () - " + person1.getName ());
   System. out. println ("person1.getAge () - " + person1.getAge ());
}
}

class Person {
private String name;
private int age;

public void setName(String userName){
   if (userName.isEmpty ()){
       System. out. println ("Please, add your name!");
   } else {
       name = userName;
   }
 }
public String getName(){
   return name;
}

public void setAge(int userAge){
   if (userAge <= 0){
       System. out. println ("Please, add your age!");
   } else {
       age = userAge;
   }
}
public int getAge() {
   return age;
}

void speak() {
   System. out. println ("My name is " + name + ", and I am " + age + " years old.");
}
}

 

 

Вывод в консоль:

 

Please, add your name!

Please, add your age!

My name is null, and I am 0 years old.

person1.getName () - null

person1.getAge () - 0

 

 

Урок 19: Ключевое слово this.

https://www.youtube.com/watch?v=sPPaDe_5fcQ&list=PLAma_mKffTOSUkXp26rgdnC0PicnmnDak&index=19 public class Lesson19 {
public static void main(String[] args) {
   Human human1 = new Human ();
   human1.setName ("Tom");
   human1.setAge (18);
   human1.getInfo ();
}
}
  class Human{
private String name;
private int age;

public void setName(String myName){
   name = myName;
}
public String getName(){
   return name;
}

public void setAge(int myAge){
   age = myAge;
}
public int getAge() {
    return age;
}

public void getInfo(){
    System. out. println (name + " - " + age);
}
 }

 

 

Вывод в консоль:

 

Tom - 18

 

 

Используем в коде ключевое слово this.

this указывает, что this.name - это private String name;

так же this вызывает Объект внутри класса

 

private String name;

public void setName(String name){
this.name = name;
}

 

 

public class Lesson19 {
public static void main(String[] args) {
   Human human1 = new Human ();
   human1.setName ("Tom");
   human1.setAge (18);
   human1.getInfo ();
}
}
  class Human{
private String name;
private int age;

public void setName(String name){
   this. name = name;
}
public String getName(){
   return name;
}

public void setAge(int age){
   this. age = age;
}
public int getAge() {
    return age;
}

public void getInfo(){
    System. out. println (name + " - " + age);
}
 }

 

 

Вывод в консоль:

 

Tom - 18

 

 

Урок 20: Конструкторы.

https://www.youtube.com/watch?v=Muytoo-x-KM&list=PLAma_mKffTOSUkXp26rgdnC0PicnmnDak&index=20 public class Lesson19 {
public static void main(String[] args) {
   Human human1 = new Human ();
}
}
  class Human{
// Конструктор по умолчанию.
/*
У конструктора нет типа данных.
Имя конструктора всегда совпадает с именем класса
и оно всегда пишется с большой буквы.
*/
public Human(){
    System. out. println ("Hello from the first Constructor!");
}
 }

 

 

Вывод в консоль:

 

Hello from the first Constructor!

 

 

Перегрузка конструкторов

 

public class Lesson19 {
public static void main(String[] args) {
   Human human1 = new Human ();
   // Hello from the first Constructor!
  
Human human2 = new Human ("Bob");
   // Hello from the second Constructor!
  
Human human3 = new Human ("Bob", 45);
   // Hello from the third Constructor!
}
}
  class Human{
private String name;
private int age;

/*
Перегрузка конструкторов - это наличие конструкторов с ОДНИМ ИМЕНЕМ, но с РАЗНЫМИ ПАРАМЕТРАМИ. */ // Конструктор по умолчанию.
public Human(){
    System. out. println ("Hello from the first Constructor!");
    this. name = "Xxx";
    this. age = 0;
}

public Human(String name){
    System. out. println ("Hello from the second Constructor!");
    this. name = name;
}
public Human(String name, int age){
    System. out. println ("Hello from the third Constructor!");
    this. name = name;
    this. age = age;
}
 }

 

Вывод в консоль:

 

Hello from the first Constructor!

Hello from the second Constructor!

Hello from the third Constructor!

 

 



Поделиться:


Последнее изменение этой страницы: 2020-11-11; просмотров: 84; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.144.252.201 (0.011 с.)