Title: Java Abstract Class Example - Java Code Geeks
Open Graph Title: Java Abstract Class Example - Java Code Geeks
Description: In this tutorial, we will discuss abstraction in java through examples. We are also going to talk about abstract class vs interface implementation in java.
Open Graph Description: In this tutorial, we will discuss abstraction in java through examples. We are also going to talk about abstract class vs interface implementation in java.
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/java-abstract-class-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/java-abstract-class-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/java-abstract-class-example/"},"author":{"name":"Sotirios-Efstathios Maneas","@id":"https://examples.javacodegeeks.com/#/schema/person/03673b064b32807176478bd144079be1"},"headline":"Java Abstract Class Example","datePublished":"2014-01-22T14:00:21+00:00","dateModified":"2023-11-09T12:39:14+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/java-abstract-class-example/"},"wordCount":976,"commentCount":2,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/java-abstract-class-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","articleSection":["Java Basics"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/java-abstract-class-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/java-abstract-class-example/","url":"https://examples.javacodegeeks.com/java-abstract-class-example/","name":"Java Abstract Class Example - Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/java-abstract-class-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/java-abstract-class-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2014-01-22T14:00:21+00:00","dateModified":"2023-11-09T12:39:14+00:00","description":"In this tutorial, we will discuss abstraction in java through examples. We are also going to talk about abstract class vs interface implementation in java.","breadcrumb":{"@id":"https://examples.javacodegeeks.com/java-abstract-class-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/java-abstract-class-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/java-abstract-class-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/java-abstract-class-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Java Basics","item":"https://examples.javacodegeeks.com/category/java-development/java-basics/"},{"@type":"ListItem","position":4,"name":"Java Abstract Class Example"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/03673b064b32807176478bd144079be1","name":"Sotirios-Efstathios Maneas","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2013/10/Stathis-Maneas-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2013/10/Stathis-Maneas-96x96.jpg","caption":"Sotirios-Efstathios Maneas"},"description":"Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.","sameAs":["https://www.cs.utoronto.ca/~smaneas/","https://www.facebook.com/stathis.maneas","https://linkedin.com/in/smaneas"],"url":"https://examples.javacodegeeks.com/author/stathis-maneas/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Java Basics","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/java-basics\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2014-01-22T16:00:21+02:00","datePublished":"2014-01-22T16:00:21+02:00","dateModified":"2023-11-09T14:39:14+02:00","headline":"Java Abstract Class Example","name":"Java Abstract Class Example","keywords":[],"url":"https:\/\/examples.javacodegeeks.com\/java-abstract-class-example\/","description":"In this tutorial, we will discuss abstraction in java through examples. We are also going to talk about abstract class vs interface implementation in Java. Data abstraction is the process of","copyrightYear":"2014","articleSection":"Java Basics","articleBody":"\nIn this tutorial, we will discuss abstraction in java through examples. We are also going to talk about abstract class vs interface implementation in Java. \n\n\n\nData abstraction is the process of hiding certain details and showing only essential information to the user. We can have abstraction with using either abstract classes or interfaces.\n\n\n\nAn abstract class is a class that is declared using the abstract keyword and it cannot be instantiated. It can be used only as a super-class for those classes that extend the abstract class. The default functionality of the class still exists, with its fields, methods and constructors being accessed in the same way as with the other classes.\n\n\n\nMoreover, an abstract class may contain methods without any implementation, called abstract methods. The declaration of an abstract method starts with the abstract keyword and ends with a semicolon, instead of the method\u2019s body. If a class contains an abstract method, either declared or inherited, it must be declared as an abstract class.\n\n\n\nA class that extends an abstract class must implement all its abstract methods (if any). Otherwise, the sub-class must be declared as abstract as well. Finally, any implementation of an abstract method can be overridden by additional sub-classes.\n\n\n\nYou can also check this tutorial in the following video:\n\n\n\n Java Abstract Class Example - Video\n\n\n\nThe last things to mention are that abstract classes can also implement methods, despite providing just their signature and that an abstract class may have static fields and static methods.\n\n\n\nIn this example, we use the following tools on a Windows 7 platform:\n\n\n\n\nEclipse Kepler Service Release 1\n\n\n\nJava 1.7.0_51\n\n\n\n\n1. Using a Java Abstract class\n\n\n\nThe purpose of an abstract class is to specify the default functionality of an object and let its sub-classes to explicitly implement that functionality. Thus, it stands as an abstraction layer that must be extended and implemented by the corresponding sub-classes.\n\n\n\nA sample example of using an abstract class is the following. We declare an abstract class, called Instrument:\n\n\n\nInstrument.java\n\n\n\n\n\n\n\n\n\n1\n2\n3\n4\n5\n\n\n\nabstract class Instrument {\n protected String name;\n \n abstract public void play();\n}\n\n\n\n\n\n\n\n\n\n\nAs we can observe, an Instrument object contains a field name and a method called play, that must be implemented by a sub-class.\n\n\n\nNext, we define a sub-class called StringedInstrument that extends the Instrument class and adds an extra field called numberOfStrings:\n\n\n\nStringedInstrument.java\n\n\n\n\n\n\n\n\n\n1\n2\n3\n\n\n\nabstract class StringedInstrument extends Instrument {\n protected int numberOfStrings;\n}\n\n\n\n\n\n\n\n\n\n\nFinally, we add two more classes that implement the functionality of a StringedIntrument, called ElectricGuitar and ElectricBassGuitar accordingly. The definition of these newly added classes is shown below:\n\n\n\nElectricGuitar.java\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n\n\n\npublic class ElectricGuitar extends StringedInstrument {\n \n public ElectricGuitar() {\n super();\n this.name = \"Guitar\";\n this.numberOfStrings = 6;\n }\n \n public ElectricGuitar(int numberOfStrings) {\n super();\n this.name = \"Guitar\";\n this.numberOfStrings = numberOfStrings;\n }\n \n @Override\n public void play() {\n System.out.println(\"An electric \" + numberOfStrings + \"-string \" + name\n + \" is rocking!\");\n }\n}\n\n\n\n\n\n\n\n\n\n\nElectricBassGuitar.java\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n\n\n\npublic class ElectricBassGuitar extends StringedInstrument {\n \n public ElectricBassGuitar() {\n super();\n this.name = \"Bass Guitar\";\n this.numberOfStrings = 4;\n }\n \n public ElectricBassGuitar(int numberOfStrings) {\n super();\n this.name = \"Bass Guitar\";\n this.numberOfStrings = numberOfStrings;\n }\n \n @Override\n public void play() {\n System.out.println(\"An electric \" + numberOfStrings + \"-string \" + name\n + \" is rocking!\");\n }\n}\n\n\n\n\n\n\n\n\n\n\nFinally, we create a new class called Execution that contains a single main method:\n\n\n\nExecution.java\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n\n\n\nimport main.java.music.ElectricBassGuitar;\nimport main.java.music.ElectricGuitar;\n \npublic class Execution {\n \n public static void main(String[] args) {\n ElectricGuitar guitar = new ElectricGuitar();\n ElectricBassGuitar bassGuitar = new ElectricBassGuitar();\n \n guitar.play();\n bassGuitar.play();\n \n guitar = new ElectricGuitar(7);\n bassGuitar = new ElectricBassGuitar(5);\n \n guitar.play();\n bassGuitar.play();\n }\n}\n\n\n\n\n\n\n\n\n\n\nIn this example, we create two different instances of an ElectricGuitar and an ElectricBassGuitar classes and we call their play methods. A sample execution of the aforementioned main method is shown below:\n\n\n\nAn electric 6-string Guitar is rocking!\nAn electric 4-string Bass Guitar is rocking!\nAn electric 7-string Guitar is rocking!\nAn electric 5-string Bass Guitar is rocking!\n\n\n\n1.1 The Purpose of Abstract Classes\n\n\n\nThe purpose of abstract classes is to function as base classes which can be extended by subclasses to create a full implementation.\n\n\n\nDue to this feature, an Abstract Class is being used in scenarios where a complete implementation can be further broken down into a set of repetitive steps with few unique steps.\n\n\n\nOne such example will be, of URL Processor application which extract the HTML of the website hosted at the URL.\n\n\n\nURLProcessorBase.java\n\n\n\npackage URLProcessor;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.net.URLConnection;\npublic abstract class URLProcessorBase {\n public void process(URL url) throws IOException {\n URLConnection urlConnection = url.openConnection();\n InputStream input = urlConnection.getInputStream();\n try {\n processURLData(input);\n } finally {\n input.close();\n }\n }\n protected abstract void processURLData(InputStream input)\n throws IOException;\n}\n\n\n\n\nThis is a base class that contains the methods used for the implementation of the URL processor.\n\n\n\nNow we can have the multiple subclasses of this base class based on the kind of processing that needs to be done on the website hosted at the URL provided as input.\n\n\n\nIn our example code, we are extracting the HTML passed as the response when we call the URL.\n\n\n\nURLProcessorImpl.java\n\n\n\npackage URLProcessor;\nimport java.io.IOException;\nimport java.io.InputStream;\npublic class URLProcessorImpl extends URLProcessorBase {\n @Override\n protected void processURLData(InputStream input) throws IOException {\n int data = input.read();\n while (data != -1) {\n System.out.print((char) data);\n data = input.read();\n }\n }\n}\n\n\n\n\nNow the main driver code.\n\n\n\nDriver.java\n\n\n\npackage URLProcessor;\nimport java.io.IOException;\nimport java.net.URL;\npublic class Driver {\n public static void main(String[] args) throws IOException {\n System.out.println(\"Driver Code for URL Processor Application using Abstract Class Method\");\n System.out.println(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\");\n System.out.println();\n URLProcessorImpl urlProcessor = new URLProcessorImpl();\n urlProcessor.process(new URL(\"https:\/\/abhiit89.github.io\/\"));\n System.out.println();\n System.out.println(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\");\n }\n}\n\n\n\n\nThe output of the driver program is shown below. \n\n\n\nOutput of Driver.java\n\n\n\nIf we apply a new implementation of the URLProcessorBase class, as shown below.\n\n\n\nURLProcessorImplToExtractDataLength.java\n\n\n\npackage URLProcessor;\nimport java.io.IOException;\nimport java.io.InputStream;\npublic class URLProcessorImplToExtractDataLength extends URLProcessorBase {\n @Override\n protected void processURLData(InputStream input) throws IOException {\n byte[] data = input.readAllBytes();\n System.out.print(data.length);\n }\n}\n\n\n\n\nURLProcessorImplToExtractDataLength.java is another implementation of the base class URLProcessorBase.java which calculates the length alone of the retrieved data. This implementation in a way enforces the SRP (Single Responsibility Principle).\n\n\n\nWe can override the original driver class to include this new implementation, but for the sake of clarity, a new driver class called the LengthDriver.java is created.\n\n\n\n LengthDriver.java\n\n\n\npackage URLProcessor;\nimport java.io.IOException;\nimport java.net.URL;\npublic class LengthDriver {\n public static void main(String[] args) throws IOException {\n System.out.println(\"Driver Code for URL Processor Application to Extract length of Retrieved Data using Abstract Class Method\");\n System.out.println(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\");\n System.out.println();\n URLProcessorImplToExtractDataLength metaProcessor = new URLProcessorImplToExtractDataLength();\n metaProcessor.process(new URL(\"https:\/\/abhiit89.github.io\/\"));\n System.out.println();\n System.out.println(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\");\n }\n}\n\n\n\n\nThe output of LengthDriver.java is shown in the snapshot below.\n\n\n\nThe output of LengthDriver.java\n\n\n\nThis covers the examples related to the Abstract Class.\n\n\n\n2. Java Abstract Class vs Interface\n\n\n\nIn this section, we are going to talk about abstract class vs interface implementation. Java provides and supports the creation of abstract classes and interfaces. \n\n\n\nAs we stated at the beginning, we can achieve the abstraction by using either abstract classes or interfaces. Both implementations share some common features, but they differ in the following features:\n\n\n\n\nAll methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.\n\n\n\nA class may implement a number of Interfaces but can extend only one abstract class.\n\n\n\nIn order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the subclass must also be declared as abstract.\n\n\n\nAbstract classes can implement interfaces without even providing the implementation of interface methods.\n\n\n\nVariables declared in a Java interface is by default final. An abstract class may contain non-final variables.\n\n\n\nMembers of a Java interface are public by default. A member of an abstract class can either be private, protected or public.\n\n\n\nAn interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated but can be invoked if it contains the main method.\n\n\n\n\nYou can learn more about the abstract class vs interface implementation by reading this example.\n\n\n\n3. Download the Eclipse Project\n\n\n\nThat was a tutorial about the Java Abstract Class.\n\n\n\nDownload\nThe Eclipse project of the Java Abstract Class Example: Java Abstract Class Example\n\n\n\nLast updated on Mar. 18th, 2020\n","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-abstract-class-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Sotirios-Efstathios Maneas","url":"https:\/\/examples.javacodegeeks.com\/author\/stathis-maneas\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:author | https://www.facebook.com/stathis.maneas |
| article:published_time | 2014-01-22T14:00:21+00:00 |
| article:modified_time | 2023-11-09T12:39:14+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Sotirios-Efstathios Maneas |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Sotirios-Efstathios Maneas |
| twitter:label2 | Est. reading time |
| twitter:data2 | 6 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1