Concrete class in java

Конкретный класс в Java

В этом кратком руководствеwe’ll discuss the term “concrete class” in Java.

Сначала дадим определение термину. Затем мы увидим, чем он отличается от интерфейсов и абстрактных классов.

2. Что такое конкретный класс?

A concrete class is a class that we can create an instance of, using the new keyword.

Другими словами, этоfull implementation of its blueprint. Конкретный класс завершен.

Представьте себе, например, классCar :

public class Car < public String honk() < return "beep!"; >public String drive() < return "vroom"; >>

Поскольку все его методы реализованы, мы называем его конкретным классом и можем создавать его экземпляры:

Некоторые примеры конкретных классов из JDK:HashMap, HashSet, ArrayList, and LinkedList.

3. Java абстракция против Бетонные классы

Not all Java types implement all their methods, though. Эта гибкость, также называемаяabstraction, позволяет нам думать в более общих терминах о предметной области, которую мы пытаемся моделировать.

В Java мы можем достичь абстракции, используя интерфейсы и абстрактные классы.

Давайте получше рассмотрим конкретные классы, сравнив их с другими.

3.1. Интерфейсы

An interface is a blueprint for a class. Или, другими словами, это коллекция невыполненных сигнатур методов:

Обратите внимание, что он использует ключевое словоinterface вместоclass.

ПосколькуDriveable — это нереализованные методы, мы не можем создать его экземпляр с помощью skeywordnew .

Но,concrete classes like Car can implement these methods.

JDK предоставляет ряд интерфейсов, напримерMap, List, and Set.

3.2. Абстрактные классы

An abstract class is a class that has unimplemented methods,, хотя на самом деле он может иметь оба:

public abstract class Vehicle < public abstract String honk(); public String drive() < return "zoom"; >>

Обратите внимание, что мы помечаем абстрактные классы ключевым словомabstract.

Опять же, посколькуVehicle имеет нереализованный методhonk, мы не сможем использовать skeywordnew .

Некоторые примеры абстрактных классов из JDK:AbstractMap and AbstractList.

3.3. Бетонные классы

Напротив,concrete classes don’t have any unimplemented methods. Независимо от того, унаследованы реализации или нет, до тех пор, пока у каждого метода есть реализация, класс конкретен.

Конкретные классы могут быть такими же простыми, как наш предыдущий примерCar. Они также могут реализовывать интерфейсы и расширять абстрактные классы:

public class FancyCar extends Vehicle implements Driveable < public String honk() < return "beep"; >>

КлассFancyCar предоставляет реализацию дляhonk и наследует реализациюdrive отVehicle.

As such, it has no unimplemented methods. Следовательно, мы можем создать экземпляр классаFancyCar с ключевым словомnew.

FancyCar car = new FancyCar();

Или, проще говоря, все классы, которые не являются абстрактными, мы можем назвать конкретными классами.

4. Резюме

В этом коротком уроке мы узнали о конкретных классах и их спецификациях.

Кроме того, мы показали различия между интерфейсами и конкретными и абстрактными классами.

Источник

Concrete Class in Java

Java Course - Mastering the Fundamentals

Concrete classes are Java classes that have code that implements all their methods, and method bodies are complete. Concrete classes in Java are known as 100% implemented classes . A concrete class can be instantiated as an object (like any other Java class).

What is a Concrete Class?

  • A concrete class in java is a class that has all its methods implemented. For any class to be classified as concrete, it cannot have any unimplemented methods.
  • Concrete classes can extend abstract class in Java or implement interfaces, but they must implement all the methods of the abstract class or interface they inherit.
  • We can create an object of concrete class using the new keyword.
  • A concrete class is an abstract class if it has even one abstract method, i.e. an unimplemented method because it doesn’t meet the condition of being a concrete class.
  • Concrete classes implement all methods and, in most cases, they inherit an abstract class or implement an interface. Java’s final class is a class that cannot be inherited, so it’s possible to declare concrete classes as final classes.
  • As a concrete class inherits or implements all the methods from an abstract class or an interface, it can also be called a 100% implemented class in Java. Java methods from concrete classes are inherited or completely implemented from abstract classes or interfaces, which helps achieve 100% abstraction.

Syntax of Concrete Class in Java

A concrete class in Java is any such class that has the implementation of all of its inherited members either from an interface or abstract class Here is the basic syntax of the Concrete class:

Here, C is a concrete class that extends abstract class A and implements interface C. Class C has implemented methods from both class A and interface B.

Simple Concrete Class

Now, let’s see how we can implement a simple concrete class using java code.

In the above code, the ConcreteCalculator class has 4 methods that perform arithmetic operations. All four methods add, subtract, multiply, divide are implemented and return the result. As all the methods of the class have been implemented ConcreteCalculator is a concrete class.

Example

The image below shows 4 classes Shape, Circle, Triangle, and Square . The shape is an abstract class with two unimplemented methods area(), perimeter() . The other three classes extend class Shape and implement both the methods area() and perimeter() of the abstract class. Hence, the classes Circle, Triangle, and Square are concrete classes.

concrete-class-extend-abstract-class-example

Concrete Class Which Extends an Abstract Class

Before seeing the code implementation of a concrete class that extends an Abstract class let’s understand what an abstract class means.

Abstraction in Java:

Abstraction is a process of hiding implementation and showing only essential details to the user. Abstraction is used in the case of banking applications to hide crucial details from end-users.

Abstract Class in Java:

  • Abstract class in java is a class that is declared using the abstract keyword.
  • It contains abstract methods which means it has incomplete or unimplemented methods.
  • Abstract classes can have abstract as well as non-abstract methods.
  • We cannot create objects of an abstract class to use abstract class methods abstract class needs to be inherited.

Let’s consider a scenario. The shape is an abstract class with two unimplemented methods area(), perimeter() . The other three classes extend class Shape and implement both the methods area() and perimeter() of the abstract class. Hence, the classes Circle, Triangle, and Square are concrete classes.

Let’s implement the above example of concrete classes using the java programming language.

In the above code, Shape is a abstract class with abstract methods area() and perimeter() . Classes Circle , Triangle , and Square inherit the abstract class shape and implement both abstract methods. As the classes Circle, Triangle and Square have all the methods implemented they are Concrete Classes.

Concrete Class Which Implements an Interface

First, let’s understand the Interface in java. Interface:

  • Interface in Java is a mechanism used to achieve abstraction.
  • Interface is said to be a blueprint of a class. It contains only abstract methods and variables.
  • Interface doesn’t have a method body.
  • Interface is used to achieve abstraction. It can also be used to implement multiple inheritances.

In the above code DemoInterface is an interface implemented by the abstract class DemoAbstract . The concrete class DemoConcrete implements the methods inherited from both the interface and the abstract class.

Java Abstraction vs. Concrete Classes

Abstract class in Java Concrete class in Java
Abstract class can have unimplemented methods. Concrete class cannot have unimplemented methods.
Abstract class cannot be instantiated i.e. we cannot create an object of an abstract class. Concrete class in java can be instantiated i.e. we can create an object of an abstract class using the new keyword.
We can declare an abstract class using the abstract keyword. Declaration of a concrete class is the same as of any normal class in java using the class keyword.
It is impossible to create an abstract class without incomplete methods as an abstract class without any abstract method will be a normal java class. On the other hand, concrete class in java should not have a single incomplete method.
Abstract class cannot be declared as a final class. The reason is final class cannot be inherited and abstract classes are meant to be inherited and then used. Concrete class can be declared as a final class as they have implementation for all the methods and need not be inherited.
Abstract class should have abstract methods. A concrete class implements all the abstract(unimplemented) methods of its parent abstract class.

Conclusion

  • Concrete classes in Java are fully implemented classes that implement all the methods.
  • Every method that a concrete class contains must be implemented. A concrete class may extend an abstract class or implement an interface.
  • To instantiate a concrete class in Java, the new keyword is used.
  • A concrete class can also be declared as a final class.

Источник

Concrete class in Java

A concrete class is a class that has an implementation for all of its methods. It is a complete class, who implements all methods from abstract classes or interfaces.

It is a complete class and can be instantiated. Any class which is not abstract is a concrete class. e.g

 package com.javacodestuffs.concrete; public class Calculator < public int multiply(int a, int b) < return a * b; >static int add(int a, int b) < return a + b; >public static void main(String args[]) < Calculator calc = new Calculator(); int product = calc.multiply(51, 123); int sum = calc.add(123, 51); System.out.println("Product of numbers is : " + product); System.out.println("Sum of numbers is : " + sum); >> $javac com/javacodestuffs/concrete/Calculator.java $java -Xmx128M -Xms16M com/javacodestuffs/concrete/Calculator Product of numbers is : 6273 Sum of numbers is : 174 

Abstract Classes

An abstract class is a class that contains both unimplemented methods and implemented methods, but it is incomplete.

There are many examples of Abstract Classes in JDK Like AbstractMap, AbstractSet, etc.

 abstract class Product implements MathOperations < public int add(int x, int y); //unimplemented method public int multiply(int x, int y) < return x * y; >> 

Interfaces

In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types.

Interfaces cannot be instantiated, they can only be implemented by classes or extended by other interfaces.

The concrete class extends an abstract class

 package com.javacodestuffs.concrete; interface MathOperations < public int multiply(int x, int y); public int add(int x, int y); public int square(int x); >abstract class Product implements MathOperations < // product of two numbers public int multiply(int x, int y) < return x * y; >> // concrete class public class Calculator extends Product < public int add(int x, int y) < return x + y; >public int square(int x) < return x * x; >public static void main(String args[]) < Calculator calc = new Calculator(); int product = calc.multiply(51, 123); int sum = calc.add(123, 51); int square = calc.square(11); System.out.println("product of numbers are : " + product); System.out.println("Sum of numbers is : " + sum); System.out.println("Square of number is : " + square); >> $javac com/javacodestuffs/concrete/Calculator.java $java -Xmx128M -Xms16M com/javacodestuffs/concrete/Calculator product of numbers are : 6273 Sum of numbers is : 174 Square of number is : 121 

We have seen we have interface MathOperations with 3 methods. The product is abstract class unable to implement all methods as it is abstract, implements only single method public int multiply(int x, int y).

But Calculator is a concrete class implements all methods which are not implemented by his parent i.e Product class.

Differences between interfaces and concrete and abstract classes.

In this article, we have seen the Concrete class in Java with examples.

Источник

Читайте также:  Кому нужны java разработчики
Оцените статью