Abstract classes and interfaces in JAVA
Abstract classes and interfaces, although they have significant differences, have in common with what defines classes one or more methods that classes should implement.
Abstract class in java to work within a class hierarchy, classes that extend (inherit) them, i.e. Its subclasses, while the interface is running, work with any class it connects to, regardless of the class hierarchy.
Those methods that are required to be applied (completed) in significant classes are "abstract" within the interface and abstract classes, that is, they are listed without a body of methods. There is only a title line of methods, no body.
The idea is that the user only uses proof of what a particular method can do, but not how it works, ie. what is happening in the body of the method.
For example. a complete method that, for example, calculates the area of a circle would be:
Abstract class in java to work within a class hierarchy, classes that extend (inherit) them, i.e. Its subclasses, while the interface is running, work with any class it connects to, regardless of the class hierarchy.
Those methods that are required to be applied (completed) in significant classes are "abstract" within the interface and abstract classes, that is, they are listed without a body of methods. There is only a title line of methods, no body.
The idea is that the user only uses proof of what a particular method can do, but not how it works, ie. what is happening in the body of the method.
For example. a complete method that, for example, calculates the area of a circle would be:
public double areaOfACircle(double r) {
//Area
double A= r*r*Math.PI;
return A;
}double A= r*r*Math.PI;
return A;
This would actually be an implemented method of seeing what it can do and how it can do it.
Within an abstract class, an abstract method would look like:
Within an abstract class, an abstract method would look like:
public abstract double areaOfACircle(double r) ;
We see that it has only the declaration, not the body of the method. The official word abstract must be added within the declaration.
So the user sees what is sufficient to know "about the method". See method name, parameters to be sent to method, and return type.
As the method calculates the area of the circle, the user does not see if the method is abstract.
Within the interface would be:
So the user sees what is sufficient to know "about the method". See method name, parameters to be sent to method, and return type.
As the method calculates the area of the circle, the user does not see if the method is abstract.
Within the interface would be:
public double areaOfACircle(double r) ;
What is difference between abstract class and interface
The difference is that the interface does not have to use the word abstract. This is because in abstract classes not all methods need to be abstract, so to distinguish between abstract stands the word "abstract".
Within the interface, all methods are abstract, so the word "abstract" does not have to be.
We see that there is some abstraction in both.
Within the interface, all methods are abstract, so the word "abstract" does not have to be.
We see that there is some abstraction in both.
Abstraction concept in java. What is abstraction?
Abstraction is the process of hiding implementation details and showing the user only functionality. In other words, only important things are shown to the user, and the internal details remain hidden.
There are two ways to achieve abstraction in java
There are two ways to achieve abstraction in java
- Abstract class (0 to 100%)
- Interface (100%)
Abstract class in java - properties
- The class is declared with the keyword abstract
- It can have abstract and non-abstract methods (methods with the body).
- Used in the class hierarchy
- An abstract class object cannot be instantiated.
- If a class inherits (extends) an abstract class and not all abstract methods are implemented in it, then it is also an abstract class.
- Abstract classes are formed with the aim of being necessarily inherited, ie. to have their own subclasses in which abstract methods will be implemented.
Video lessons
Video 1: Abstract classes and interfaces 1
In this video, you can see the basic characteristics of abstract classes and interfaces, their similarities and differences. The use of abstract classes is also shown in the example Geometric shapes
Abstract class and class inheritance in java
Let's say we want to create a hierarchy of classes that represent various geometric surfaces: square, rectangle, parallelogram, triangle, circle, trapezoid. We also want in the test class to create those objects and calculate surfaces.
A class should be created for each of these shapes, in which we will extract the properties and methods of all objects that represent one of these geometric shapes. In order to best create a hierarchy of classes, we will start with a class in which we specify what is common to all geometric shapes. Then they would make classes for specific forms that would inherit this class. Let's call the common subclass GeometricShape, and the derived classes: Square, Triangle, Circle, etc.
A class should be created for each of these shapes, in which we will extract the properties and methods of all objects that represent one of these geometric shapes. In order to best create a hierarchy of classes, we will start with a class in which we specify what is common to all geometric shapes. Then they would make classes for specific forms that would inherit this class. Let's call the common subclass GeometricShape, and the derived classes: Square, Triangle, Circle, etc.
At the top of the class hierarchy is the abstract class GeometricShape, which represents a common class with all geometric shapes, and is inherited by classes that represent specific surfaces: Triangle, Square, and Circle.
Let's look at a method that is to calculate the surface of a particular geometric shape. Since the GeometricShape does not know what shape it is, the surface cannot yet be calculated, so this method is defined as abstract in that class. In the class diagram, abstract methods are displayed with the font style "Italic".
An abstract class is necessarily made inherited. An abstract class object cannot be instantiated, we can declare and initialize to null. For example. can be declared as follows:
Let's look at a method that is to calculate the surface of a particular geometric shape. Since the GeometricShape does not know what shape it is, the surface cannot yet be calculated, so this method is defined as abstract in that class. In the class diagram, abstract methods are displayed with the font style "Italic".
An abstract class is necessarily made inherited. An abstract class object cannot be instantiated, we can declare and initialize to null. For example. can be declared as follows:
GeometricShape shape =null;
Only objects of inherited classes can be instantiated, for example:
Square square=new Square();
Triangle triangle=new Triangle();
Circle circle=new Circle();
Triangle triangle=new Triangle();
Circle circle=new Circle();
The calculateArea () method is implemented in all three subclasses of the class. In all these subclasses, the method will have the same title line, but a different implementation, that is, the formula for calculating the area that is inside the body of the method is different for each of the specific surfaces.
In the abstract class, complete methods can be found, as in ordinary classes, as well as variables. We can see that in the abstract class there are variables of area of shape A type double and privacy modifiers protected and color, type Color and privacy modifiers private. They will be inherited by the other three subclasses.
In the abstract class, complete methods can be found, as in ordinary classes, as well as variables. We can see that in the abstract class there are variables of area of shape A type double and privacy modifiers protected and color, type Color and privacy modifiers private. They will be inherited by the other three subclasses.
Abstract classes - syntax. Class GeometricShape
public abstract class GeometricShape {
//Area of shape
protected double A;
private Color color;
abstract double calculateArea();
public Color getColor() {
}protected double A;
private Color color;
abstract double calculateArea();
public Color getColor() {
return color;
} Interface-basic concepts
It is actually a set of rules that every class that implements it must obey. The interface contains a list of method declarations, therefore, only the title lines of the methods, without the body. These methods are abstract. without its implementation. Constants but not variable data can be found in the interface.
Example of interface Syntax:
public interface GeometricShape {
private String BLUE="Blue"; //Blue color is defined as a constant
private String RED="Red"; //Red color is defined as a constant
public double calculateArea(); //an abstract method that calculates the area of a shape
public Color getColor(); //an abstract method that gives color
public String getName(); //an abstract method that returns name of the shape
}private String RED="Red"; //Red color is defined as a constant
public double calculateArea(); //an abstract method that calculates the area of a shape
public Color getColor(); //an abstract method that gives color
public String getName(); //an abstract method that returns name of the shape
We see that in the title line, as opposed to classes, the official word interface is used instead of the official say class when defining an interface. The GeometricShape Interface has two abstract methods of calculateArea (), getColor () and getName (), which will be implemented in those classes that would be associated with the GeometricShape interface. Blue and red constants representing the defined surface colors are also defined.
Similar to the example described in abstract classes, we will associate this interface with classes that represent concrete surfaces. The following class diagram shows these links:
Similar to the example described in abstract classes, we will associate this interface with classes that represent concrete surfaces. The following class diagram shows these links:
In the example shown, the Square and Circle shapes are connected to the GeometricShape interface, not the Triangle class. In this example, it is necessary to calculate the area for a square and a circle, not for a triangle. For interfaces we can choose which class to bind the interface to, while in the case of examples with abstract classes we would have to implement the surface method in all subclasses that inherited the abstract class GeometricShape, whether we wanted it or not (see Figure 1).
For example, to associate the Square class with an interface in the title line, we need to add the official word interface and the class name that the interface needs to implement:
For example, to associate the Square class with an interface in the title line, we need to add the official word interface and the class name that the interface needs to implement:
public class Square implements GeometricShape
{
}
{
We can see that the class is highlighted in red indicating an error, as abstract methods from the interface have not yet been implemented. So this class is committed to implementing these methods (contract). Now let's add these methods:
package geometricshapesinterfaces;
import java.util.Math;
public class Square implements GeometricShape
{
double a;
//Constructor with parameters
public Square(double a) {
//Implemented method from the interface GeometricShape to calculate the area of a square
@Override
public double calculateArea()
{
//Implemented method from the GeometricForm that returns color
@Override
public String getColor()
{
//Implemented method from interface GeometricForm that returns a name
@Override
public String getName()
{
}
import java.util.Math;
public class Square implements GeometricShape
{
double a;
//Constructor with parameters
public Square(double a) {
this.a = a;
}//Implemented method from the interface GeometricShape to calculate the area of a square
@Override
public double calculateArea()
{
double A=a*a;
return A;
}return A;
//Implemented method from the GeometricForm that returns color
@Override
public String getColor()
{
return BLUE; //Color is available because it is defined in the interface associated with this class
}//Implemented method from interface GeometricForm that returns a name
@Override
public String getName()
{
return "Square";
}In the Square class, abstract methods from the GeometricShape interface must be implemented. Similarly the class circuit also implements the same interface, meaning it will have the same methods, but the implementation of those methods will not be the same. the getName () method returns "Circle" instead of "Square", the calculateArea() method calculates the area of a circle with the appropriate formula for the area of the circle, and the getColor () method returns the color of the circle, not the square. Circle class:
package geometricshapesinterfaces;
import java.util.Math;
public class Circle implements GeometricShape
{
double r;
//Constructor with parameters
public Square(double r) {
//Implemented method from the interface GeometricShape to calculate the area of a square
@Override
public double calculateArea()
{
//Implemented method from the GeometricForm that returns color
@Override
public String getColor()
{
//Color is available because it is defined in the interface associated with this class
@Override
public String getName()
{
}
import java.util.Math;
public class Circle implements GeometricShape
{
double r;
//Constructor with parameters
public Square(double r) {
this.r = r;
}//Implemented method from the interface GeometricShape to calculate the area of a square
@Override
public double calculateArea()
{
double A=r*r*Math.PI;
return A;
}return A;
//Implemented method from the GeometricForm that returns color
@Override
public String getColor()
{
return RED; //Color is available because it is defined in the interface associated with this class
}//Color is available because it is defined in the interface associated with this class
@Override
public String getName()
{
return "Circle";
}Within the main class, i.e. test class we will create the objects of a square and a circle, give the necessary initial data, that is, a page for a square and a radius for a circle, and then calculate the surfaces and print it on the screen.
Main test class:
Main test class:
package geometricshapesinterfaces;
public class GeometricShapesInterfaces
{
public class GeometricShapesInterfaces
{
Square k=new Square(10);
Triangle t=new Triangle(10, 5);
System.out.println("Area of the shape: "+k.getName()+" is "+
k.calculateArea()+", Color:"+k.getColor());
System.out.println("Area of the shape: "+t.getName()+" is "+
t.calculateArea()+", Color:"+t.getColor());
GeometrijcShape k2=new Square(45);
System.out.println("Area of the shape: "+((Kvadrat)k2).getName()+" is "+
k2.calculateArea()+", Color:"+k2.getColor());
}Triangle t=new Triangle(10, 5);
System.out.println("Area of the shape: "+k.getName()+" is "+
k.calculateArea()+", Color:"+k.getColor());
System.out.println("Area of the shape: "+t.getName()+" is "+
t.calculateArea()+", Color:"+t.getColor());
GeometrijcShape k2=new Square(45);
System.out.println("Area of the shape: "+((Kvadrat)k2).getName()+" is "+
k2.calculateArea()+", Color:"+k2.getColor());
The last object created is an instance of the Square class because the constructor of the Square class was called, however, the GeometricShape interface was specified for the data type.
So here we see that an interface can also be used as a data type for an object, in case the class of that object implemented the said interface.
So here we see that an interface can also be used as a data type for an object, in case the class of that object implemented the said interface.
Example: Geometric solid
Create a hierarchy of classes of geometric bodies: Prizma, Pyramid, Ball. In the main test class, create one object of these bodies, specify the required data and calculate the areas and volumes.
Consider the following method for the Prism class to calculate the volume of a right rectangular prism with the base perimeters a and b and height of prism H:
The method consists of a title line and a body. The title line contains the privacy modifier (public), the return value type (float) method name (volume), and parameters (in this example, the method is parameterless). The body of the method is enclosed by a pair of parentheses "{}" and the body contains an implementation of the method, that is, commands that resolve the task set before the method, in this case calculating the volume of the prism.
This method would most likely be called from another class via a Prizm class object:
This method would most likely be called from another class via a Prizm class object:
What is interface?
When we put the operator "." , after the object name to call the method ("volume ()"), only the name, methods, parameters and return value appear, ie. what is defined in the "title line" of the method. It should be noted that the body of the method or the "implementation" of the method is not visible here. But the implementation of the method for someone outside is not "important", it is important what that method does, what value it return and what data it needs. This is what defines the method in the method title bar and is part of an external "interface".
The interface would therefore be a set of such title lines of methods defined in a separate file and all of these methods work together for a specific task. Since methods in the interface do not have "implementation" they are abstract. In the observed example, these would be methods that define a geometric shape, that is, the name of the geometric shape, surface and volume. Consider now two classes representing the prism and the pyramid. Both classes should have the same methods, name (), area () and volume ().
The interface would therefore be a set of such title lines of methods defined in a separate file and all of these methods work together for a specific task. Since methods in the interface do not have "implementation" they are abstract. In the observed example, these would be methods that define a geometric shape, that is, the name of the geometric shape, surface and volume. Consider now two classes representing the prism and the pyramid. Both classes should have the same methods, name (), area () and volume ().
and the second class Pyramid:
It can be seen that both classes implement the same 3 methods name (), surfaceArea () and volume (), therefore they have the same external "interface", but the implementation of the methods differs. If we were to separate the set of title lines of these methods into a separate file, as some concept of the methods that each geometric shape should have, we could make these abstract methods as an interface:
These abstract methods will be "implemented" in every class we associate with that class via the official Java language implements. In this case, these are the Prism and Pyramid classes, which both represent the "Geometric Shape" and both "implement" the same interface
i
When classes connect to an interface, abstract methods must be implemented in the classes. This can be seen in the previous figures.
Interfaces-examples in java
In the example described above, the use of an interface from start to finish is shown. and defining and using it. There are a number of predefined interfaces in the API (installed public class library) that just need to be associated with a class. For example. if we want to respond to a change in ComboBox selection, the class in which it resides should implement the ItemListener interface, which has an abstracted Abstract Method ItemStateChanged ();
In the example of a movie club rental application, on a form that shows all the rentals of a selected user, there is a ComboBox filled with the names of all users in the database
In the example of a movie club rental application, on a form that shows all the rentals of a selected user, there is a ComboBox filled with the names of all users in the database
Changing the selected user in ComboBox should also be reflected in the rental chart. The rental form, therefore, needs to implement the ItemListener interface, that is, its Abstract ItemStateChanged method
Here we see that a ComboBox is passed to an object whose data type in this case is not a class but an interface ItemListener. If it were a class, the object would be created using the official word new as shown here and by calling the constructor jawa.awt.event.ItemListener (). Since ItemListener is not a class but an interface that contains an abstract, non-implemented itemStateChanged method, it must be implemented here, as shown in the figure.
In response to a ComboBox click, the User Change Method (evt)
In response to a ComboBox click, the User Change Method (evt)
In this method, via the evt object that carries event information, the reference of the ComboBox that produced the event (source) is first retrieved, and then the selected item in that ComboBox is retrieved: selObj.
After verifying that the selected item is an object of type User, an attribute is extracted from that object, which represents the user id that was selected and the corresponding data is extracted from the database.
After verifying that the selected item is an object of type User, an attribute is extracted from that object, which represents the user id that was selected and the corresponding data is extracted from the database.
Abstract classes-general terms
The purpose of abstract classes is similar to that of an interface except that the interface can be bound to any class, while abstract classes are used in the class hierarchy. inheritance. Here are some other differences with respect to interfaces:
- For interfaces, all methods are abstract unlike a class, which, in order to be abstract, must have at least one abstract method.
- abstract methods must be implemented in one of the classes that inherit the abstract, that is, within the class hierarchy, while interfaces can be implemented in any class regardless of the class hierarchies
- An abstract class must be inherited, because no object of an abstract class can be made, but only some inherited class in which all abstract methods are implemented
- the abstract of the method of the abstract class must have the official word abstract, while the interface does not have to, since all methods are certainly abstract
- An abstract class is a class where the official word abstract is given in front of the class name
Example: Geometry
Text: Create an abstract class An element that defines a generic geometric element that has a color attribute and an abstract method to return the element type. Then create two classes Circle and Rectangle that describe the specific element types and inherit the abstract Element class. In the main class, create one object in the class Circle and Rectangle and write down the elements.
Solution:
Abstract class An element has two color attributes and a name, one ordinary method (color getter) and two abstract methods that will be implemented in the inherited classes, once it is known which element is in question.
Abstract class An element has two color attributes and a name, one ordinary method (color getter) and two abstract methods that will be implemented in the inherited classes, once it is known which element is in question.
This class will be inherited by the Circle and Rectangle classes. The Circle class looks like:
If the abstract method getName were not implemented here, the compiler would report an error. It must be implemented as well as the getShape () method, which in this case returns an object of class Ellipse2D.Double from the java.awt.geom public package. The constructor is passed the parameters of the coordinate of the position of the circle, as well as the radius, and on this basis an object of the circle is formed.
The Rectangle class is left to the reader to make it himself for practice.
Objects of this class will be made and thus this class tested in the main class:
The Rectangle class is left to the reader to make it himself for practice.
Objects of this class will be made and thus this class tested in the main class:
Previous
|< Inheritance of classes |