Скачать презентацию Успадкуваня класів В термінології Java клас від якого Скачать презентацию Успадкуваня класів В термінології Java клас від якого

OOP_L5.ppt

  • Количество слайдов: 31

Успадкуваня класів В термінології Java клас, від якого успадкований похідний клас називається суперкласом. Успадкований Успадкуваня класів В термінології Java клас, від якого успадкований похідний клас називається суперкласом. Успадкований клас називається підкласом. A B

Успадкуваня класів (загальна форма) сlass ім’я_підкласу extends ім’я_суперкласу { // тіло класу } Успадкуваня класів (загальна форма) сlass ім’я_підкласу extends ім’я_суперкласу { // тіло класу }

Успадкуваня класів (приклад) class Simple. Inheritance { // Create a superclass. public static void Успадкуваня класів (приклад) class Simple. Inheritance { // Create a superclass. public static void main(String args[]) { class A { A super. Ob = new A(); int i, j; B sub. Ob = new B(); void showij() { // The superclass may be used by itself. System. out. println("i and j: " + i + " " + j); super. Ob. i = 10; } super. Ob. j = 20; } System. out. println("Contents of super. Ob: "); super. Ob. showij(); // Create a subclass by extending class A. System. out. println(); /* The subclass has access to all public members of class B extends A { its superclass. */ int k; sub. Ob. i = 7; void showk() { sub. Ob. j = 8; System. out. println("k: " + k); sub. Ob. k = 9; } System. out. println("Contents of sub. Ob: "); sub. Ob. showij(); void sum() { sub. Ob. showk(); System. out. println("i+j+k: " + (i+j+k)); System. out. println(); } System. out. println("Sum of i, j and k in sub. Ob: "); } sub. Ob. sum(); } }

Успадкуваня класів (приклад) Contents of super. Ob: i and j: 10 20 Contents of Успадкуваня класів (приклад) Contents of super. Ob: i and j: 10 20 Contents of sub. Ob: i and j: 7 8 k: 9 Sum of i, j and k in sub. Ob: i+j+k: 24

Доступ до членів класу і успадкуваня // Create a superclass A { int i; Доступ до членів класу і успадкуваня // Create a superclass A { int i; // public be default private int j; // private to A void setij(int x, int y) { i = x; j = y; } } // A's j is not accessible here. class B extends A { int total; void sum() { total = i + j; // ERROR, j is not accessible here } } class Access { public static void main(String args[]) { B sub. Ob = new B(); sub. Ob. setij(10, 12); sub. Ob. sum(); System. out. println("Total is " + sub. Ob. total); } }

Доступ до членів класу і успадкуваня class Box { double width; double height; double Доступ до членів класу і успадкуваня class Box { double width; double height; double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob. width; height = ob. height; depth = ob. depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } class Box. Weight extends Box { double weight; // weight of box // constructor for Box. Weight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class Demo. Box. Weight { public static void main(String args[]) { Box. Weight mybox 1 = new Box. Weight(10, 20, 15, 34. 3); Box. Weight mybox 2 = new Box. Weight(2, 3, 4, 0. 076); double vol; vol = mybox 1. volume(); System. out. println("Volume of mybox 1 is " + vol); System. out. println("Weight of mybox 1 is " + mybox 1. weight); System. out. println(); vol = mybox 2. volume(); System. out. println("Volume of mybox 2 is " + vol); System. out. println("Weight of mybox 2 is " + mybox 2. weight); } }

Доступ до членів класу і успадкуваня Volume of mybox 1 is 3000. 0 Weight Доступ до членів класу і успадкуваня Volume of mybox 1 is 3000. 0 Weight of mybox 1 is 34. 3 class Color. Box extends Box { int color; // color of box Volume of mybox 2 is 24. 0 Weight of mybox 2 is 0. 076 } Color. Box(double w, double h, double d, int c) { width = w; height = h; depth = d; color = c; }

Посилання змінної суперкласу на об’єкт підкласу class Ref. Demo { public static void main(String Посилання змінної суперкласу на об’єкт підкласу class Ref. Demo { public static void main(String args[]) { Box. Weight weightbox = new Box. Weight(3, 5, 7, 8. 37); Box plainbox = new Box(); double vol; vol = weightbox. volume(); System. out. println("Volume of weightbox is " + vol); System. out. println("Weight of weightbox is " + weightbox. weight); System. out. println(); // assign Box. Weight reference to Box reference plainbox = weightbox; vol = plainbox. volume(); // OK, volume() defined in Box System. out. println("Volume of plainbox is " + vol); /* The following statement is invalid because plainbox does not define a weight member. */ // System. out. println("Weight of plainbox is " + plainbox. weight); } }

Використання ключового слова super Для виклику конструктора суперкласу. 2. Для звертання до члена суперкласу, Використання ключового слова super Для виклику конструктора суперкласу. 2. Для звертання до члена суперкласу, прихованого членом підкласу. 1.

Використання ключового слова super для виклику конструктора суперкласу super (список_аргументів); Оператор super() завжди повинен Використання ключового слова super для виклику конструктора суперкласу super (список_аргументів); Оператор super() завжди повинен бути першим виконуваним в середині конструктора підкласу

Використання ключового слова super для виклику конструктора суперкласу (приклад) class Box { private double Використання ключового слова super для виклику конструктора суперкласу (приклад) class Box { private double width; private double height; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob. width; height = ob. height; depth = ob. depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } // Box. Weight now fully implements all constructors. class Box. Weight extends Box { double weight; // weight of box // construct clone of an object Box. Weight(Box. Weight ob) { // pass object to constructor super(ob); weight = ob. weight; } // constructor when all parameters are specified Box. Weight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } // default constructor Box. Weight() { super(); weight = -1; }

Використання ключового слова super для виклику конструктора суперкласу (приклад) // constructor used when cube Використання ключового слова super для виклику конструктора суперкласу (приклад) // constructor used when cube is created Box. Weight(double len, double m) { super(len); weight = m; } } class Demo. Super { public static void main(String args[]) { Box. Weight mybox 1 = new Box. Weight(10, 20, 15, 34. 3); Box. Weight mybox 2 = new Box. Weight(2, 3, 4, 0. 076); Box. Weight mybox 3 = new Box. Weight(); // default Box. Weight mycube = new Box. Weight(3, 2); Box. Weight myclone = new Box. Weight(mybox 1); double vol; vol = mybox 1. volume(); System. out. println("Volume of mybox 1 is " + vol); System. out. println("Weight of mybox 1 is " + mybox 1. weight); System. out. println(); vol = mybox 2. volume(); System. out. println("Volume of mybox 2 is " + vol); System. out. println("Weight of mybox 2 is " + mybox 2. weight); System. out. println(); vol = mybox 3. volume(); System. out. println("Volume of mybox 3 is " + vol); System. out. println("Weight of mybox 3 is " + mybox 3. weight); System. out. println(); vol = myclone. volume(); System. out. println("Volume of myclone is " + vol); System. out. println("Weight of myclone is " + myclone. weight); System. out. println(); vol = mycube. volume(); System. out. println("Volume of mycube is " + vol); System. out. println("Weight of mycube is " + mycube. weight); System. out. println(); } }

Використання ключового слова super для виклику конструктора суперкласу (приклад) Volume of mybox 1 is Використання ключового слова super для виклику конструктора суперкласу (приклад) Volume of mybox 1 is 3000. 0 Weight of mybox 2 is 34. 3 Volume of mybox 1 is 24. 0 Weight of mybox 2 is 0. 076 Volume of mybox 1 is -1. 0 Weight of mybox 2 is -1. 0 Volume of myclone is 3000. 0 Weight of myclone is 34. 3 Volume of mycube is 27. 0 Weight of mycube is 2. 0

Використання ключового слова super для звертання до члена суперкласу super. член_класу Тут член_класу – Використання ключового слова super для звертання до члена суперкласу super. член_класу Тут член_класу – метод або змінна екземпляра

Використання ключового слова super для звертання до члена суперкласу (приклад) class A { int Використання ключового слова super для звертання до члена суперкласу (приклад) class A { int i; } // Create a subclass by extending class A. class B extends A { int i; // this i hides the i in A class Use. Super { public static void main(String args[]) { B sub. Ob = new B(1, 2); sub. Ob. show(); } B(int a, int b) { super. i = a; // i in A i = b; // i in B } void show() { System. out. println("i in superclass: " + super. i); System. out. println("i in subclass: " + i); } } } i in subclass: 1 i in superclass: 2

Створення багаторівневої ієрархії class Box { private double width; private double height; private double Створення багаторівневої ієрархії class Box { private double width; private double height; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob. width; height = ob. height; depth = ob. depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // default constructor Box. Weight() { super(); weight = -1; } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } // Add weight. class Box. Weight extends Box { double weight; // weight of box // construct clone of an object Box. Weight(Box. Weight ob) { // pass object to constructor super(ob); weight = ob. weight; } // constructor when all parameters are specified Box. Weight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; }

Створення багаторівневої ієрархії // constructor used when cube is created Box. Weight(double len, double Створення багаторівневої ієрархії // constructor used when cube is created Box. Weight(double len, double m) { super(len); weight = m; } } // Add shipping costs class Shipment extends Box. Weight { double cost; // construct clone of an object Shipment(Shipment ob) { // pass object to constructor super(ob); cost = ob. cost; } // constructor when all parameters are specified Shipment(double w, double h, double d, double m, double c) { super(w, h, d, m); // call superclass constructor cost = c; } // default constructor Shipment() { super(); cost = -1; } // constructor used when cube is created Shipment(double len, double m, double c) { super(len, m); cost = c; } }

Створення багаторівневої ієрархії class Demo. Shipment { public static void main(String args[]) { Shipment Створення багаторівневої ієрархії class Demo. Shipment { public static void main(String args[]) { Shipment shipment 1 = new Shipment(10, 20, 15, 10, 3. 41); Shipment shipment 2 = new Shipment(2, 3, 4, 0. 76, 1. 28); double vol; vol = shipment 1. volume(); System. out. println("Volume of shipment 1 is " + vol); System. out. println("Weight of shipment 1 is " + shipment 1. weight); System. out. println("Shipping cost: $" + shipment 1. cost); System. out. println(); vol = shipment 2. volume(); System. out. println("Volume of shipment 2 is " + vol); System. out. println("Weight of shipment 2 is " + shipment 2. weight); System. out. println("Shipping cost: $" + shipment 2. cost); } } Volume of shipment 1 is 3000. 0 Weight of shipment 1 10. 0 Shipping cost: $3. 41 Volume of shipment 1 is 24. 0 Weight of shipment 1 0. 76 Shipping cost: $1. 28

Порядок виклику конструкторів class A { A() { System. out. println( Порядок виклику конструкторів class A { A() { System. out. println("Inside A's constructor. "); } } // Create a subclass by extending class A. class B extends A { B() { System. out. println("Inside B's constructor. "); } } // Create another subclass by extending B. class C extends B { C() { System. out. println("Inside C's constructor. "); } } class Calling. Cons { public static void main(String args[]) { C c = new C(); } } Inside A's constructor. Inside B's constructor. Inside C's constructor.

Перевизначення методів class A { int i, j; A(int a, int b) { i Перевизначення методів class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System. out. println("i and j: " + i + " " + j); } // display k -- this overrides show() in A void show() { System. out. println("k: " + k); } } class Override { public static void main(String args[]) { B sub. Ob = new B(1, 2, 3); sub. Ob. show(); // this calls show() in B } } } class B extends A { int k; k: 3 B(int a, int b, int c) { super(a, b); k = c; }

Перевизначення методів class A { int i, j; A(int a, int b) { i Перевизначення методів class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System. out. println("i and j: " + i + " " + j); } // overload show() void show(String msg) { System. out. println(msg + k); } } class Override { public static void main(String args[]) { B sub. Ob = new B(1, 2, 3); sub. Ob. show("This is k: "); // this calls show() in B sub. Ob. show(); // this calls show() in A } } } // Create a subclass by extending class A. class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } This is k : 3 i and j: 1 2

Перезавантаження методів class A { int i, j; A(int a, int b) { i Перезавантаження методів class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System. out. println("i and j: " + i + " " + j); } // overload show() void show(String msg) { System. out. println(msg + k); } } class Override { public static void main(String args[]) { B sub. Ob = new B(1, 2, 3); sub. Ob. show("This is k: "); // this calls show() in B sub. Ob. show(); // this calls show() in A } } } // Create a subclass by extending class A. class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } This is k: 3 i and j: 1 2

Динамічна диспетчеризація методів // Dynamic Method Dispatch class A { void callme() { System. Динамічна диспетчеризація методів // Dynamic Method Dispatch class A { void callme() { System. out. println("Inside A's callme method"); } } class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A class B extends A { // override callme() void callme() { System. out. println("Inside B's callme method"); } } class C extends A { // override callme() void callme() { System. out. println("Inside C's callme method"); } } r = a; // r refers to an A object r. callme(); // calls A's version of callme r = b; // r refers to a B object r. callme(); // calls B's version of callme r = c; // r refers to a C object r. callme(); // calls C's version of callme } } Inside A's callme method Inside B's callme method Inside C's callme method

Використання перевизначення методів // override area for rectangle double area() { System. out. println( Використання перевизначення методів // override area for rectangle double area() { System. out. println("Inside Area for Rectangle. "); return dim 1 * dim 2; } // Using run-time polymorphism. class Figure { double dim 1; double dim 2; Figure(double a, double b) { dim 1 = a; dim 2 = b; } double area() { System. out. println("Area for Figure is undefined. "); return 0; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System. out. println("Inside Area for Triangle. "); return dim 1 * dim 2 / 2; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } }

Використання перевизначення методів class Find. Areas { public static void main(String args[]) { Figure Використання перевизначення методів class Find. Areas { public static void main(String args[]) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; figref = r; System. out. println("Area is " + figref. area()); figref = t; System. out. println("Area is " + figref. area()); figref = f; System. out. println("Area is " + figref. area()); } } Inside Area for Rectangle. Area is 45 Inside Area for Triangle. Area is 40 Area for Figure is undefined. Area is 0

Використання абстрактних класів аbstract тип ім’я(список_параметрів) Використання абстрактних класів аbstract тип ім’я(список_параметрів)

Використання абстрактних класів abstract class A { abstract void callme(); // concrete methods are Використання абстрактних класів abstract class A { abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System. out. println("This is a concrete method. "); } } class B extends A { void callme() { System. out. println("B's implementation of callme. "); } } class Abstract. Demo { public static void main(String args[]) { B b = new B(); b. callmetoo(); } } B's implementation of callme. This is a concrete method.

Використання абстрактних класів abstract class Figure { double dim 1; double dim 2; Figure(double Використання абстрактних класів abstract class Figure { double dim 1; double dim 2; Figure(double a, double b) { dim 1 = a; dim 2 = b; } // area is now an an abstract method abstract double area(); } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System. out. println("Inside Area for Rectangle. "); return dim 1 * dim 2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System. out. println("Inside Area for Triangle. "); return dim 1 * dim 2 / 2; } }

Використання ключового слова final із успадкуванням Для запобігання перевизначення Для запобігання успадкування Використання ключового слова final із успадкуванням Для запобігання перевизначення Для запобігання успадкування

Використання ключового слова final із успадкуванням Для запобігання перевизначення class A { final void Використання ключового слова final із успадкуванням Для запобігання перевизначення class A { final void meth() { System. out. println("This is a final method. "); } } class B extends A { void meth() { // ERROR! Can't override. System. out. println("Illegal!"); } } Для запобігання успадкування final class A { //. . . } // The following class is illegal. class B extends A { // ERROR! Can't subclass A //. . . }

Клас Object Методи класу 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Клас Object Методи класу 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. Object clone () boolean equals(Object object) void finalize () Class get. Class() int hash. Code () void notify. All() String to. String() void wait(long rnilliseconds, int nanoseconds)