Advertisement
ElenaR1

prog

Jan 26th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.30 KB | None | 0 0
  1. In C++, if a class has at least one pure virtual function, then the class becomes abstract. Unlike C++, in Java, a separate keyword abstract is used to make a class abstract.
  2.  
  3. https://www.geeksforgeeks.org/abstract-classes-in-java/
  4. // An example abstract class in Java
  5. abstract class Shape {
  6.     int color;
  7.  
  8.     // An abstract function (like a pure virtual function in C++)
  9.     abstract void draw();  
  10. }
  11.  
  12.  
  13. abstract class Base {
  14.     abstract void fun();
  15. }
  16. class Derived extends Base {
  17.     void fun() { System.out.println("Derived fun() called"); }
  18. }
  19. class Main {
  20.     public static void main(String args[]) {
  21.    
  22.         // Uncommenting the following line will cause compiler error as the
  23.         // line tries to create an instance of abstract class.
  24.         // Base b = new Base();
  25.  
  26.         // We can have references of Base type.
  27.         Base b = new Derived();
  28.         b.fun();
  29.     }
  30. }
  31. Output:
  32.  
  33. Derived fun() called
  34. 2) Like C++, an abstract class can contain constructors in Java. And a constructor of abstract class is called when an instance of a inherited class is created. For example, the following is a valid Java program.
  35. // An abstract class with constructor
  36. abstract class Base {
  37.     Base() { System.out.println("Base Constructor Called"); }
  38.     abstract void fun();
  39. }
  40. class Derived extends Base {
  41.     Derived() { System.out.println("Derived Constructor Called"); }
  42.     void fun() { System.out.println("Derived fun() called"); }
  43. }
  44. class Main {
  45.     public static void main(String args[]) {
  46.     Derived d = new Derived();
  47.     }
  48. }
  49. Output:
  50.  
  51. Base Constructor Called
  52. Derived Constructor Called
  53. 3) In Java, we can have an abstract class without any abstract method. This allows us to create classes that cannot be instantiated, but can only be inherited.
  54. // An abstract class without any abstract method
  55. abstract class Base {
  56.     void fun() { System.out.println("Base fun() called"); }
  57. }
  58.  
  59. class Derived extends Base { }
  60.  
  61. class Main {
  62.     public static void main(String args[]) {
  63.         Derived d = new Derived();
  64.         d.fun();
  65.     }
  66. }
  67. Output:
  68.  
  69. Base fun() called
  70.  
  71.  
  72. Всеки клас, който има поне един абстрактен метод, трябва да бъде абстрактен. Логично, нали? Обратното, обаче не е в сила. Възможно е да дефинираме клас като абстрактен дори когато в него няма нито един абстрактен метод.
  73.  
  74.  
  75. Интерфейс в джава
  76. Понятието интерфейс предствлява следващата стъпка след абстрактния клас. Интерфейса представлява декларация на съвкупност от методи и константи. Методите са декларирани с прототиповете си - тип на резултата, име, брой и тип на аргументите. Te като нямат тяло - няма описание на метода. . От интерфейс не може да бъде създаван обект. Целта на на интерфейса е деклариране на методи, които трябва задължително да присъстват в класовете, които ги използват. Както и класа интерфейса дефинира нов тип. Всеки обект, който прилага този интерфейс може да се разглежда като обект от този тип и следователно притежава всички методи и константи декларирани в интерфейса.  
  77. Важно:
  78. • Интерфейса може да наследява (extends) един или повече интерфейси.
  79. • Интрефейса може да дефинира данни, но те са задължитено константи - "static" и "final".
  80. • Методите в интерфейса са винаги само абстрактни.
  81. • Методите в интерфейса са задължително public (независимо дали са декларирани или не като такива)
  82. https://www.geeksforgeeks.org/interfaces-in-java/
  83. Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body).  
  84. • Interfaces specify what a class must do and not how. It is the blueprint of the class.
  85. • An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement.
  86. If a class implements an interface and does not provide method bodies for all functions specified in the interface, then class must be declared abstract.
  87.  
  88. To declare an interface, use interface keyword. It is used to provide total abstraction. To implement interface use implements keyword.
  89. Why do we use interface ?
  90. • It is used to achieve total abstraction.
  91. • Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance .
  92. • It is also used to achieve loose coupling.
  93. • Interfaces are used to implement abstraction. So the question arises why use interfaces when we have abstract classes?
  94. The reason is, abstract classes may contain non-final variables, whereas variables in interface are final, public and static.
  95.  
  96.  
  97.  
  98. import java.io.*;
  99.  
  100. interface Vehicle {
  101.    
  102.     // all are the abstract methods.
  103.     void changeGear(int a);
  104.     void speedUp(int a);
  105.     void applyBrakes(int a);
  106. }
  107.  
  108. class Bicycle implements Vehicle{
  109.    
  110.     int speed;
  111.     int gear;
  112.    
  113.     // to change gear
  114.     @Override
  115.     public void changeGear(int newGear){
  116.        
  117.         gear = newGear;
  118.     }
  119.    
  120.     // to increase speed
  121.     @Override
  122.     public void speedUp(int increment){
  123.        
  124.         speed = speed + increment;
  125.     }
  126.    
  127.     // to decrease speed
  128.     @Override
  129.     public void applyBrakes(int decrement){
  130.        
  131.         speed = speed - decrement;
  132.     }
  133.    
  134.     public void printStates() {
  135.         System.out.println("speed: " + speed
  136.             + " gear: " + gear);
  137.     }
  138. }
  139.  
  140. class Bike implements Vehicle {
  141.    
  142.     int speed;
  143.     int gear;
  144.    
  145.     // to change gear
  146.     @Override
  147.     public void changeGear(int newGear){
  148.        
  149.         gear = newGear;
  150.     }
  151.    
  152.     // to increase speed
  153.     @Override
  154.     public void speedUp(int increment){
  155.        
  156.         speed = speed + increment;
  157.     }
  158.    
  159.     // to decrease speed
  160.     @Override
  161.     public void applyBrakes(int decrement){
  162.        
  163.         speed = speed - decrement;
  164.     }
  165.    
  166.     public void printStates() {
  167.         System.out.println("speed: " + speed
  168.             + " gear: " + gear);
  169.     }
  170.    
  171. }
  172. class GFG {
  173.    
  174.     public static void main (String[] args) {
  175.    
  176.         // creating an inatance of Bicycle
  177.         // doing some operations
  178.         Bicycle bicycle = new Bicycle();
  179.         bicycle.changeGear(2);
  180.         bicycle.speedUp(3);
  181.         bicycle.applyBrakes(1);
  182.        
  183.         System.out.println("Bicycle present state :");
  184.         bicycle.printStates();
  185.        
  186.         // creating instance of bike.
  187.         Bike bike = new Bike();
  188.         bike.changeGear(1);
  189.         bike.speedUp(4);
  190.         bike.applyBrakes(3);
  191.        
  192.         System.out.println("Bike present state :");
  193.         bike.printStates();
  194.     }
  195. }
  196. Output;
  197.  
  198. Bicycle present state :
  199. speed: 2 gear: 2
  200. Bike present state :
  201. speed: 1 gear: 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement