• 0

[JAVA] Abstract Class Concept


Question

A teacher gave me this lecture with some questions, and I am somewhat confused.

Say we have a hierarchy like:

Object

|

+---A

|

+---B

|

+---C

and we made these methods in Class A:

public abstract void method1();

public abstract void method2(int i);

so... these questions were presented to us:

(a) If class B does not override any of the two methods above, can class B be compiled cleanly? If so, can an object be created from class B? If not, explain why not.

(b) Now assume that class B overrides method1 given above. Can class B be compiled cleanly? If so, can an object be created from class B? If not, explain why not.

© Now assume that class C overrides method2 given above (with the assumption that B overrides method1, as discussed in part(b)). Can class C be compiled cleanly? If so, can an object be created from class C? If not, explain why not.

(d) In defining class A described above, must the abstract modifier be used in the 1st line of the class definition (or is it optional given that it has abstract method(s) in it)?

(e) In defining method1 and method2 described above, must the abstract modifier be used in the method statement (or is it optional given that it has no method body)?

Ok, so if a subclass, which would be B, doesn't override the abstract methods, it becomes an abstract class, correct? But I'm not really sure if it can create an object or not, I don't believe it can, but can someone at least elaborate on this.

Any help would be appreciated.

Link to comment
https://www.neowin.net/forum/topic/233031-java-abstract-class-concept/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

same as he said.

"Abstract" tell classes that inherit from it they it must implement these abstract methods.

Abstract class and methods can not be created as they have no implementation. They are classes designed to be inherited by a subclass

eg.

class Shape 
{
   abstract void drawMe()
  {
     //sub classes should implement this
     //no code here
  }
}

class Triangle extends Shape
{
   void drawMe()
  {
    // draw a triangle here
    //put your code here
   }
}

class Square extends Shape
{
   void drawMe()
  {
    // draw a square here
    // put your code here
   }
}

so now as long as we know the object is instanceof object we can call the draw method

somefunction(Shape x)
{
   //since we call drawMe() cause we know all subclasses of shape implement this method
   x.drawMe();
}

someFunction2(Object x)
{

  // we can cast if object is instance of shape and call drawMe() method
  if (x instanceof Shape)
    (x(Shape)).drawMe();
}

main
{
   Triangle t = new Triangle();
   Square s = new Square();


   //we can now call these functions with these objects
   somefunction(t);
   somefunction(s);
   
   somefunction2(t);
   somefunction2(s);
}

  • 0

(a) If class B does not override any of the two methods above, can class B be compiled cleanly? If so, can an object be created from class B? If not, explain why not.

(b) Now assume that class B overrides method1 given above. Can class B be compiled cleanly? If so, can an object be created from class B? If not, explain why not.

? Now assume that class C overrides method2 given above (with the assumption that B overrides method1, as discussed in part(b)). Can class C be compiled cleanly? If so, can an object be created from class C? If not, explain why not.

(d) In defining class A described above, must the abstract modifier be used in the 1st line of the class definition (or is it optional given that it has abstract method(s) in it)?

(e) In defining method1 and method2 described above, must the abstract modifier be used in the method statement (or is it optional given that it has no method body)?

Answers

a) No, it cannot it must provide implementation for both methods, so it MUST override the two methods

b) It still cannot be, because the implementation for the other abstract method isn't overriden.

c) Yes, class C can be compiled, because Class B overrides one method and essentially it's inherited that abstract method as well, and Class C inherited the overriden method and and also provides an implementation for that other method.

d) No, it doesn't have to be used, providing there is at least one or more abstract methods, that class becomes an abstract class as opposed to an concrete class

e) No, it must be declared abstract to force the sub-class to override the method, otherwise it's a simple method that has emtpy implementation and when invoked will do nothing.

  • 0
a) No, it cannot it must provide implementation for both methods, so it MUST override the two methods

I don't think this is right. You can have a chain of abstract classes, but you cannot create an object of an abstract class. Once all abstract methods have been overridden, you can create objects.

  • 0

Actually, all I wanted was some explanation of abstract classes, but I got some of it before you guys answered the questions, but thanks for the input, I really feel like I understand abstract classes better than the lecture and notes that were given.

  • 0
I don't think this is right. You can have a chain of abstract classes, but you cannot  create an object of an abstract class. Once all abstract methods have been overridden, you can create objects.

584774123[/snapback]

Well yeah exactly, the question asked if B only overrided one of the abstract methods can B still be instantiated, it won't allow it, because it inherits the abstract class and is thus obliged to implement all abstract methods, or else it will whinge.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Oddly, there was a time that UFC games were culturally relevant, largely because of the graphics and gameplay that was different than the norm. But it seems like as the sport grew in popularity, gaming outlets stopped talking about the games.
    • Microsoft Edge 149.0.4022.69 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Microsoft Edge 149.0.4022.69 changelog: Fixed an issue that caused the Downloads dialog to continue displaying the "Keep/Delete" prompt for .rdp files after the download completed. Stable channel security updates are listed here. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User for 1-Year) by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where for only a limited time, you can save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1 Year) for Windows. Take control of your business finances with Intuit® QuickBooks® Desktop Pro Plus 2024 Lifetime Activation for Windows. This powerful accounting software simplifies bookkeeping, expense tracking, invoicing, and financial management—all in one intuitive platform. Designed for small business owners, freelancers, and accountants, QuickBooks® Desktop Pro Plus 2024 ensures accuracy, efficiency, and seamless transaction tracking. Stay organized, save time, and manage your finances with confidence—no subscriptions, just lifetime access! Financial and business management Comprehensive Financial Management: Gain access to a full suite of features designed to handle everything from creating invoices & managing expenses to generating reports and tracking sales. Enhanced Reporting Tools: Generate professional reports & insights to make informed financial decisions and help you stay ahead of your business goals. Job Costing: Track the profitability of specific jobs or projects. Fixed Asset Management: Track the depreciation & value of fixed assets. Customer & Vendor Management: Organize information, streamline communication & enhance customer relations. Sales Order Processing: Create & manage sales orders from start to finish. Purchase Order Processing: Create & manage purchase orders to streamline vendor payments. Improved Inventory Management: Enhanced features for tracking inventory levels & costs. Automation, integration, and support Enhanced Bank Feeds: Web Connect (manual QBO imports), works on all licenses for easier bank reconciliation Time Tracking: Track employee time to accurately calculate payroll and project costs Easy Data Import: Quickly transfer financial data from Excel or older QuickBooks® versions Why choose Intuit® QuickBooks® Desktop Pro Plus 2024? Effortless Installation: Quick and easy setup with step-by-step guidance. No Hidden Costs: One-time payment—no subscriptions or recurring fees. Direct Official Download: Access the software securely from the official QuickBooks® website. Stay Up to Date: Get the latest updates and features for optimal performance. Multilingual Support: Available in multiple languages to suit your needs. Lifetime Access: A one-time purchase means no ongoing costs. IMPORTANT: Cloud integrations (QuickBooks Payments, TurboTax, and Online logins) are NOT included. Good to know: Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: Windows Max number of device(s): 2 (for 1 user only and can't be used simultaneously) Version: 2024 (United States) 64-bit Available to both NEW and EXISTING users For US customers only Updates included An Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1-Year) for Windows: Lifetime License normally costs $536, but it can be yours for just $299.99 for a limited time, a saving of $236. There are also other plans available. For specifications, and license info please click the link below. Get Intuit QuickBooks Desktop Pro Plus 2024 for just $299.99 This is a time limited deal For US customers only. Support queries If you have queries or need support for any of the Neowin Deals, please use the contact form here. Neowin Deals are managed and sold by StackCommerce who represent Neowin on an affiliate basis. Why we post these deals We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. So for those that keep moaning and complaining, be thankful we're still online for you to even do that. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • AFAIK you shouldn't be getting a consent popup at all from Canada, so I think it is to do with a VPN or private/secure DNS.
    • From what I see it's only for Insider - preview builds. Not for everybody. So...
  • Recent Achievements

    • Week One Done
      agatameier earned a badge
      Week One Done
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      507
    2. 2
      +Edouard
      175
    3. 3
      PsYcHoKiLLa
      139
    4. 4
      ATLien_0
      90
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!