Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- https://www.geeksforgeeks.org/abstract-classes-in-java/
- // An example abstract class in Java
- abstract class Shape {
- int color;
- // An abstract function (like a pure virtual function in C++)
- abstract void draw();
- }
- abstract class Base {
- abstract void fun();
- }
- class Derived extends Base {
- void fun() { System.out.println("Derived fun() called"); }
- }
- class Main {
- public static void main(String args[]) {
- // Uncommenting the following line will cause compiler error as the
- // line tries to create an instance of abstract class.
- // Base b = new Base();
- // We can have references of Base type.
- Base b = new Derived();
- b.fun();
- }
- }
- Output:
- Derived fun() called
- 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.
- // An abstract class with constructor
- abstract class Base {
- Base() { System.out.println("Base Constructor Called"); }
- abstract void fun();
- }
- class Derived extends Base {
- Derived() { System.out.println("Derived Constructor Called"); }
- void fun() { System.out.println("Derived fun() called"); }
- }
- class Main {
- public static void main(String args[]) {
- Derived d = new Derived();
- }
- }
- Output:
- Base Constructor Called
- Derived Constructor Called
- 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.
- // An abstract class without any abstract method
- abstract class Base {
- void fun() { System.out.println("Base fun() called"); }
- }
- class Derived extends Base { }
- class Main {
- public static void main(String args[]) {
- Derived d = new Derived();
- d.fun();
- }
- }
- Output:
- Base fun() called
- Всеки клас, който има поне един абстрактен метод, трябва да бъде абстрактен. Логично, нали? Обратното, обаче не е в сила. Възможно е да дефинираме клас като абстрактен дори когато в него няма нито един абстрактен метод.
- Интерфейс в джава
- Понятието интерфейс предствлява следващата стъпка след абстрактния клас. Интерфейса представлява декларация на съвкупност от методи и константи. Методите са декларирани с прототиповете си - тип на резултата, име, брой и тип на аргументите. Te като нямат тяло - няма описание на метода. . От интерфейс не може да бъде създаван обект. Целта на на интерфейса е деклариране на методи, които трябва задължително да присъстват в класовете, които ги използват. Както и класа интерфейса дефинира нов тип. Всеки обект, който прилага този интерфейс може да се разглежда като обект от този тип и следователно притежава всички методи и константи декларирани в интерфейса.
- Важно:
- • Интерфейса може да наследява (extends) един или повече интерфейси.
- • Интрефейса може да дефинира данни, но те са задължитено константи - "static" и "final".
- • Методите в интерфейса са винаги само абстрактни.
- • Методите в интерфейса са задължително public (независимо дали са декларирани или не като такива)
- https://www.geeksforgeeks.org/interfaces-in-java/
- 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).
- • Interfaces specify what a class must do and not how. It is the blueprint of the class.
- • 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.
- • 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.
- To declare an interface, use interface keyword. It is used to provide total abstraction. To implement interface use implements keyword.
- Why do we use interface ?
- • It is used to achieve total abstraction.
- • Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance .
- • It is also used to achieve loose coupling.
- • Interfaces are used to implement abstraction. So the question arises why use interfaces when we have abstract classes?
- The reason is, abstract classes may contain non-final variables, whereas variables in interface are final, public and static.
- import java.io.*;
- interface Vehicle {
- // all are the abstract methods.
- void changeGear(int a);
- void speedUp(int a);
- void applyBrakes(int a);
- }
- class Bicycle implements Vehicle{
- int speed;
- int gear;
- // to change gear
- @Override
- public void changeGear(int newGear){
- gear = newGear;
- }
- // to increase speed
- @Override
- public void speedUp(int increment){
- speed = speed + increment;
- }
- // to decrease speed
- @Override
- public void applyBrakes(int decrement){
- speed = speed - decrement;
- }
- public void printStates() {
- System.out.println("speed: " + speed
- + " gear: " + gear);
- }
- }
- class Bike implements Vehicle {
- int speed;
- int gear;
- // to change gear
- @Override
- public void changeGear(int newGear){
- gear = newGear;
- }
- // to increase speed
- @Override
- public void speedUp(int increment){
- speed = speed + increment;
- }
- // to decrease speed
- @Override
- public void applyBrakes(int decrement){
- speed = speed - decrement;
- }
- public void printStates() {
- System.out.println("speed: " + speed
- + " gear: " + gear);
- }
- }
- class GFG {
- public static void main (String[] args) {
- // creating an inatance of Bicycle
- // doing some operations
- Bicycle bicycle = new Bicycle();
- bicycle.changeGear(2);
- bicycle.speedUp(3);
- bicycle.applyBrakes(1);
- System.out.println("Bicycle present state :");
- bicycle.printStates();
- // creating instance of bike.
- Bike bike = new Bike();
- bike.changeGear(1);
- bike.speedUp(4);
- bike.applyBrakes(3);
- System.out.println("Bike present state :");
- bike.printStates();
- }
- }
- Output;
- Bicycle present state :
- speed: 2 gear: 2
- Bike present state :
- speed: 1 gear: 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement