Advertisement
sergAccount

Untitled

Aug 23rd, 2020
1,458
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package com.spec;
  7.  
  8. import com.spec.model.SpecialStudent;
  9. import com.spec.model.Student;
  10.  
  11. /**
  12.  *
  13.  * @author Admin
  14.  */
  15. public class Test2 {
  16.    
  17.     //
  18.     public static void workWithStudent(Student s){
  19.         //
  20.         System.out.println("workWithStudent:");
  21.         System.out.println("s.name=" + s.getName());
  22.         System.out.println("s.age="  + s.getAge());
  23.         //
  24.         if(s instanceof SpecialStudent){
  25.             System.out.println("((SpecialStudent)s).getGrant()=" + ((SpecialStudent)s).getGrant());
  26.         }        
  27.     }
  28.  
  29.     public static void main(String[] args) {
  30.         // явное преобразование типов - используем оператор (ИмяТипа)
  31.         Student s = new SpecialStudent("Nick", 12);
  32.         // используем метод класса Student
  33.         System.out.println("s.name=" + s.getName());
  34.         //
  35.         // 1) нет ошибки при выполнении данного кода
  36.         // используем яное преобразование к типу SpecialStudent
  37.         double grantValue;
  38.         if(s instanceof SpecialStudent){
  39.             grantValue = ((SpecialStudent)s).getGrant();
  40.             System.out.println("grantValue=" + grantValue);
  41.         }
  42.         //s.getGrant();
  43.        
  44.         // 2) ошибку (исключение) при выполнении данного кода
  45.         Student s2 = new Student("Serg", 10);
  46.         // используем опертор instaceof для безопасного преобразования типа
  47.         if(s2 instanceof SpecialStudent){
  48.             SpecialStudent mySpecial1 = (SpecialStudent)s2;
  49.             grantValue = mySpecial1.getGrant();
  50.         }else{
  51.             System.out.println("s2 не является объектом типа SpecialStudent!!!");
  52.         }
  53.        
  54.         workWithStudent(new SpecialStudent("Nick1", 12));        
  55.         workWithStudent(new Student("Nick2", 24));
  56.        
  57.         System.out.println("OK!!!");        
  58.     }
  59.  
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement