Inheritance and extending classes - homework

Here ive got a problem, firstly i don't know why this code won't work, ive got to use the keywords abstract + extend.
Ive put this all into one .java file, when should I put a class into a different file and not place it as an inner like i have done a number of times here ?
public abstract class shape {
int pi;
int radius;
public class twoD extends shape {
twoD(int r, int p) {   //constructor for circle
radius = r;
pi = p;
public void setAreaCircle() {   // area of circle method
int circleArea = pi * radius^radius;
System.out.println(circleArea);
public void setCircumCircle() {   // circumfreanceof circle method
int circleCircum = 2 * pi^radius;
System.out.println(circleCircum);
class circle extends twoD {
public static void main(String args[]){
twoD ob = new twoD(5,10);
ob.setAreaCircle();
ob.setCircumCircle();

K ive done as suggested and added a constructor that calls its superclass contrustor but its still not working. :(
Any clues ?
public abstract class shape {
int pi;
int radius;
class twoD extends shape {
twoD(int r, int p) {   //constructor for circle
radius = r;
pi = p;
public void setAreaCircle() {   // area of circle method
int circleArea = pi * radius^radius;
System.out.println(circleArea);
public void setCircumCircle() {   // circumfreanceof circle method
int circleCircum = 2 * pi^radius;
System.out.println(circleCircum);
public class circle extends twoD {
public static void main(String args[]) {
public circle(int r, int p) {     // call to superclass constructor
super(r,p);
twoD ob = new twoD(5,10);
ob.setAreaCircle();
ob.setCircumCircle();

Similar Messages

  • Difference between inheritance and abstract class

    difference between inheritance and abstract class

    See this thread:
    http://forum.java.sun.com/thread.jspa?forumID=24&threadID=663657
    And before Post New Topic, just search in this forums. All most will get answers.

  • Re: Inheritance and Inner classes

    Sorry all,
    I forgot to include that I loose the inner classes in codesense. And
    the editor will not let me reference them.
    Thanks again,
    Stu
    "Stu Pidasso" <[email protected]> wrote in message
    news:41fe9aac$[email protected]..
    Hello all,I'm an Eclipse and Nitro newby here, and I was wondering if anyone had any
    insight into this. I'm subclassing a "Constants" class that contains some
    static variables, static methods and static inner classes. Once I
    subclass,
    and refer to my new class, I loose all the parent class' inner classes.
    Is
    there a way around this? Or, am I hosed and have to put in a bug report
    somewhere? I know that in JBuilder this functionality works fine.
    Thanks,
    Stu

    K ive done as suggested and added a constructor that calls its superclass contrustor but its still not working. :(
    Any clues ?
    public abstract class shape {
    int pi;
    int radius;
    class twoD extends shape {
    twoD(int r, int p) {   //constructor for circle
    radius = r;
    pi = p;
    public void setAreaCircle() {   // area of circle method
    int circleArea = pi * radius^radius;
    System.out.println(circleArea);
    public void setCircumCircle() {   // circumfreanceof circle method
    int circleCircum = 2 * pi^radius;
    System.out.println(circleCircum);
    public class circle extends twoD {
    public static void main(String args[]) {
    public circle(int r, int p) {     // call to superclass constructor
    super(r,p);
    twoD ob = new twoD(5,10);
    ob.setAreaCircle();
    ob.setCircumCircle();

  • Working with traits and policy classes

    I have not been able to see if anyone has raised this before from my searches of the forums but this may just be bad searching !
    I am trying to investigate how much of the traits / policies idioms of working in C++ generic programming are applicable to Java. The following trio of classes are a very striped down version of one problem I am having. It relates to the use of static methods, inheritance and generic classes.
    First a couple of classes with static methods related by inheritance.
    public class X {
      public static int get() {
        System.err.println("X.get.") ;
        return 1 ;
    public class Y extends X {
      public static int get() {
        System.err.println("Y.get.") ;
        return X.get() + 1 ;
    }Now a class that uses the types as type parameters and tries to call the static method:
    public class TypeParameterLookupSolved<A extends X> {
      private void doit() {
        System.out.println(A.get()) ;
      public static void main(final String[] args) {
        TypeParameterLookupSolved<Y> tpli = new TypeParameterLookupSolved<Y> () ;
        tpli.doit() ;
    }The output from running this is:
    X.get.
    1
    So the question is why does the call of A.get() always bind to X.get() when na�vely you would expect Y.get() to be called.
    If Java will only ever call X.get() in this instance then the policy class idiom will not work properly . Of course it may be that there is another way of doing this that I have missed.
    Thanks.

    Thanks for the correction.
    I never can get the hang of up and down in type hierarchies -- functional programming people talk a lot about top and bottom in type hierarchies and I never remember which is which. One of these days I will find a mechanism for putting the knowledge into long-term memory :-)
    Having had the epiphany of "least upper bounds", it is now trivially easy to do Java-style generic programming (which is good :-) even though it is totally different to everyone else (C++, Python, Groovy, Ruby, Nice, CL, OCAML, Haskell, . . .-- which is not so good). I am increasingly of the view that using the term Generics has been a labelling error and an unfortunate disservice to Java as it can set up a mind-set about parameterized types and "generic programming" that is fundamentally wrong. I can feel a series of short articles coming on as well as sorting out my ADS library!

  • Adf bc jar for base entity classes and extending them existing  project

    Hi,
    I am using jdev 11.1.1.0 and have created a base workspace/project and adf jar for my base entity classes.
    1. I can consume this base adf bc jar in a separate new consuming workspace and create VO based on base bc classes or create new EOs that extend base bc entity classes.
    2. Furthermore, for an existing consuming project that earlier included src/ of base entity (BC components), i can remove the dependency on bc source and bring in this new adf jar and everything including the view controller and the service/datacontrol works fine.
    The issue i am running into is as follows.
    - In the existing project (#2) above i try to create a couple of entities based on entities in my base jar; associations are automatically brought in. Note i am not overriding any attributes. My intent here is to generate .java and implement some code.
    - I then try to make my existing VOs based on the newly extended entity (VO overview->Entity Objects-> Shuttle NewEntity from Available to Selected)
    - I then try to remove the old EO from selected under VO overview->Entity Objects->Shuttle OldEntity from Selected back
    - I get a warning dialog box that says something to the effect that some viewlinks are dependent on these old EOs in this consuming project.
    - I tried to laboriously analyzed dependencies and it this dialog box does not make any sense as I have already extended EOs and the tooling should be able to let me use these
    My questions
    - Why I am not able to remove old entities from VO dependencies
    - Is it ok to leave the old EOs in "Selected" along with the newly extended EO ? What are the implications for this?
    - I also thought about extending base associations, but did not go anywhere.
    In general, I am ok with consuming an ADF BC jar that has entities etc. but not clear about removing dependencies of base EOs on VOs when entities are extended and consumed in a pre-existing project that used base entities.
    I can send a project if any PM is willing to take a look at it.
    Thanks,
    ps:
    I have already gone over the following info
    http://technology.amis.nl/blog/215/organization-of-bc4j-domain-eo-and-business-vo-package
    .. wants to create an enterprise data model in BC4J, reflecting the Enterprise Data Model set up in the RDBMS. All (or at least most) business rules will be implemented in the Middle Tier – to take the load of the database and also allow developers not comfortable with PL/SQL to define and maintain the business rules. It is clear that this means that all applications that need to access – and manipulate – the database, need to go through the BC4J foundation layer. Martijn wants to define the Entity Objects – and their business rules – only once and share that definition between different projects. Each projects can create its own ViewObjects on top of these shared Enterprise Entity Objects.
    http://radio-weblogs.com/0118231/2005/09/29.html
    I am currently working on a project for a partner where we will be using ADF BC as our model layer for a large application. In order to keep the footprint of each application module down to a reasonable size, we are intending to create a number of separate 'root' application modules for each functional area of the application. Within, these 'root' application modules we will then use nested application modules to further partition the application. All of the application modules will be accessing the same datasource and will need access to the same database objects.
    In order to separate our code between the development team and into function areas, our initial thoughts were that we would create an ADF BC model project containing Entity Objects for all of the database tables e.t.c. as these are common amongst all functional areas. We have configured all of the EOs for validation rules, defaulting values and extending doDML() as appropriate. Happy at this stage we then created a simple .jar file to deploy all of the definitions. Upon creating a new ADF BC project for each functional area we added the jar file as a library import into the new project. However when we the tried to create some new View Objects via the JDev Wizard we were unable to see the imported Entity Objects.
    Is the only way to share Entity Object definitions between different ADF BC projects to manually copy the source definition files into the new projects src directory? Since this would mean multiple copies of the same components, it could prove to be a maintenance nightmare.Is there a way of doing it without creating multiple copies of the same object definitions?
    The developer is spot on in their ideas of layering and reuse, and even has created a library for their reusable entities. This last step is not something everyone thinks to do. The missing step is known as "importing" components, so with that one extra bit of knowledge under his belt, he should be able to do exactly what he envisions. My little article called Difference Between Adding and Importing Business Components tries to explain the difference and gives the menu options to choose to perform the importing.
    Difference between adding and importing BC4J
    http://radio-weblogs.com/0118231/stories/2005/08/11/differenceBetweenAddingAndImportingBusinessComponents.html
    Working with Libraries of Reusable Business Components
    http://download.oracle.com/docs/cd/B32110_01/web.1013/b25947/bcadvgen.htm#CHEFECGD

    Hi,
    since you followed the OC4J developer guide I think this question might be better handled there as well
    OC4J
    So in case you don't get an answer here on the forum, try it on the OC4J forum
    Frank

  • Extending classes and overriding methods

    If I have a class which extends another, and overrides some methods, if I from a third class casts the extending class as the super class and calls one of the methods which gets overrided, is it the overrided method or the method of the superclass which get executed?
    Stig.

    Explicit cast can't enable the object to invoke super-class's method. Because dynamic binding is decided by the instance. The cast can just prevent you from using methods only defined in sub-class, but it does not let the object to use super-class's method, if the method's been overrided. Otherwise, the polymophism, which is one of the most beautiful feature of Object-Oriented thing, can't be achieved. As far as I know, the only way to use super-class's method is the super keyword in the sub-class, and seems no way for an object to do the same thing (I may wrong, since I haven't read the language spec).
    here's a small test:
    public class Test {
    public static void main(String[] args){
    A a = new B();
    a.method();
    ((A)a).method();
    class A{
    public void method(){
    System.out.println("A's method");
    class B extends A{
    public void method(){
    System.out.println("B's method");
    The output is:
    B's method
    B's method

  • What's the most efficient way to extend product and catalog classes?

    If I have additional product and catalog properties in a new database table, should
    I create a new class and extend the ProductItem and Catalog classes or should
    I manage these properties via the set/get property methods on the existing classes?
    Is there a difference in performance with the two approaches?

    Performance wise using the set/get property methods is going to be more
    expensive... However, I would recommend the property approach. You really
    don't want to modify or extend the provided source code. I have done this
    and the approach works out fine...
    Another approach that I have used is to create additional tables and classes
    that key of the product and catalog classes. Again with the intension that
    we don't modify provided stuff... For example, we implemented related
    products using this approach.
    "Bill" <[email protected]> wrote in message
    news:3fbcf598$[email protected]..
    >
    If I have additional product and catalog properties in a new databasetable, should
    I create a new class and extend the ProductItem and Catalog classes orshould
    I manage these properties via the set/get property methods on the existingclasses?
    Is there a difference in performance with the two approaches?

  • [svn:fx-trunk] 5223: Introduce ButtonBase and ToggleButtonBase classes and make FxButton extend ButtonBase , ToggleButtonBase extend ButtonBase, FxToggleButton, FxCheckBox, FxRadioButton extend ToggleButtonBase.as.

    Revision: 5223
    Author: [email protected]
    Date: 2009-03-10 13:10:07 -0700 (Tue, 10 Mar 2009)
    Log Message:
    Introduce ButtonBase and ToggleButtonBase classes and make FxButton extend ButtonBase, ToggleButtonBase extend ButtonBase, FxToggleButton, FxCheckBox, FxRadioButton extend ToggleButtonBase.as.
    The emphasized property and IButton are pushed down to the FxButton, so the rest of the buttons don't have them.
    QE Notes: None
    Doc Notes:
    Bugs: SDK-19671, SDK-19670
    Reviewer: Glenn
    tests: checkintests, mustella (gumbo/components)
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-19671
    http://bugs.adobe.com/jira/browse/SDK-19670
    Modified Paths:
    flex/sdk/trunk/frameworks/mxml-2009-manifest.xml
    flex/sdk/trunk/frameworks/projects/flex4/defaults.css
    flex/sdk/trunk/frameworks/projects/flex4/manifest.xml
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/ButtonBarButton.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxButton.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxCheckBox.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxRadioButton.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/FxToggleButton.as
    Added Paths:
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/baseClasses/ButtonBase.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/components/baseClasses/ToggleButtonBase.a s

  • 'My Application Page' is not allowed here because it does not extend class 'System.Web.UI.Page'

    I have a custom SharePoint 2010 solution that includes an aspx page. The aspx page in is in the /layouts folder within the solution and I created it by just adding an application page to the solution. I am trying to create a parent-child relationship between
    two different lists in SharePoint. From the parent I have a custom button on the ribbon that creates a child item with the ID of the parent stamped on it.
    The page is just a processing page that forwards on parameters from the parent to the new child item. (i.e. the ID value)
    The code generated when I add the aspx page is below:
    <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
    <%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
    <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
    <%@ Import Namespace="Microsoft.SharePoint" %>
    <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="processingpage.aspx.cs" Inherits="MY.Solution.Layouts.MY.Solution.processingpage" MasterPageFile="~/_layouts/application.master" %>
    <asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    </asp:Content>
    <asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    </asp:Content>
    <asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server"> Processing Page </asp:Content>
    <asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" > Processing Page </asp:Content>
    The code behind is as follows:
    using System;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.Utilities;
    using System.Reflection;
    namespace MY.Solution.Layouts.MY.Solution
    public partial class processingpage : LayoutsPageBase
    protected void Page_Load(object sender, EventArgs e)
    try
    //Get a reference to the SPWeb object
    SPWeb oWeb = SPContext.Current.Web;
    //Use the Parameters That Are Passed In
    SPList thisList = oWeb.Lists[new Guid(Request.QueryString["List"])];
    SPListItem thisItem = thisList.GetItemById(int.Parse(Request.QueryString["ID"]));
    sContentType = thisItem["ContentType"].ToString();
    sContentTypeID = thisItem.ContentTypeId.ToString();
    if (sContentType == "Some Content Type")
    sContentTypeID = "";
    sAIID = thisItem["ID"].ToString();
    //Redirect to newform.aspx with the Appropriate parameters.
    Context.Response.Redirect(oWeb.Url + "/Lists/Blist" + "/NewForm.aspx?AIID=" + sAIAuditID.ToString() + "&ContentTypeId=" + sContentTypeID + "&ParentItemID" + Context.Request["ID"]);
    else if (sContentType == "Some Content Type")
    sContentTypeID = "";
    sAIID = thisItem["AIID"].ToString();
    //Redirect to newform.aspx with the Appropriate parameters.
    Context.Response.Redirect(oWeb.Url + "/Lists/AList" + "/NewForm.aspx?AIID=" + sAIID.ToString() + "&ContentTypeId=" + sContentTypeID + "&ParentItemID" + Context.Request["ID"]);
    else if (sContentType == "Some Content Type")
    sContentTypeID = "";
    sAICID = thisItem["AICID"].ToString();
    //Redirect to newform.aspx with the Appropriate parameters.
    Context.Response.Redirect(oWeb.Url + "/Lists/CList" + "/NewForm.aspx?AICID=" + sAICID.ToString() + "&ContentTypeId=" + sContentTypeID + "&ParentItemID" + Context.Request["ID"]);
    else
    LoggingService.LogError("MY.Solution - Processing Page", "No Applicable Content Type Found.");
    catch (Exception ex)
    LoggingService.LogError("My.Solution - Processing Page", ex.Message);
    finally
    //DO SOME FINAL THINGS HERE WHEN REQUIRED.
    In the page I need to use Request.QueryString to get the values from the URL. But when I deploy the solution and load the page I get the error:
    'MY.Solution.Layouts.MY.Solution.processingpage' is not allowed here because it does not extend class 'System.Web.UI.Page'.
    When I change the line:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="processingpage.aspx.cs" Inherits="MY.Solution.Layouts.MY.Solution.processingpage" MasterPageFile="~/_layouts/application.master" %>
    to inherit as follows:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="processingpage.aspx.cs" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" MasterPageFile="~/_layouts/application.master" %>
    it does not work either.
    If I change it to inherit like below:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="processingpage.aspx.cs" Inherits="System.Web.UI.Page" MasterPageFile="~/_layouts/application.master" %>
    it also does not work.
    What does this error actually mean?  And why doesn't the default code generated by Visual Studio work?

    @NadeemYousuf I have tried this too and it didn't work.  
    What does the error even mean?  And why does the error appear with default Visual Studio code?  In my example I have just added a basic application page with no other code in it and it still does not work.

  • When to use inheritance and When to use Composition

    java support both inheratiance and composition .I also know "is a" and
    "has a realitionship" but there is always a problem with me to understanding whethere i have to use extends or having a object of a class has a member of othere class.
    and also "A pure OOP must support polimorphisim,inheretiance,encapluction,Abstraction and Composition" correct me if i am wrong
    thank you and have a nice day.

    Bruce Eckel, author of Thinking In Java, has this to say about composition vs. inheritance:
    When deciding between inheritance and composition, ask if you need to upcast to the base type. If not, prefer composition (member objects) to inheritance. This can eliminate the perceived need for multiple base types. If you inherit, users will think they are supposed to upcast.
    Choose composition first when creating new classes from existing classes. You should only used inheritance if it is required by your design. If you use inheritance where composition will work, your designs will become needlessly complicated.
    Bill Venners: Composition versus Inheritance
    Use inheritance (of implementation) only when the class satisfies the following criteria:
    1) "Is a special kind of," not "is a role played by a";
    2) Never needs to transmute to be an object in some other class;
    3) Extends rather than overrides or nullifies superclass;
    4) Does not subclass what is merely a utility class (useful functionality you'd like to reuse); and
    5) Within PD: expresses special kinds of roles, transactions, or things.
    -- from Java Design: Building Better Apps and Applets (2nd Edition), by Peter Coad and Mark Mayfield

  • Extending classes with private methods?

    my understanding of extending classes is that you gain all the functions and methods of that class thus You could over ride any one of them. How ever I am confused on weather or not you inherit and can over ride private methods of the class you are extending or if you have to have all methods public in an extended class.
    hope that makes sense, an example can bee seen bellow.
    package
         public class Class1
              public function apples():void
                   //some code
              private fnctuin bananas():void
                   //more code
    package
         public class Class2 extends Class 1
              override public function apples():void
                   //i changed code
              //can I over ride bananas?

    you can only override methods that would be inherited.  a private method won't be inherited:
    http://www.kirupa.com/forum/showthread.php?223798-ActionScript-3-Tip-of-the-Day/page5

  • Authoring Tool "Inherit Class" vs "New Class" vs "Extended Class" Scenario Help

    Hi Community,
    I am currently creating the ground work needed to create Self Service Portal Request Offerings to be used by end users and then take that input and automate it with Orchestrator.
    I'm pretty comfortable with the overall process of how this is done, but I was hoping to get guidance from the community to make sure that I don't waste my time by editing my existing management pack incorrectly from the beginning.
    We currently have a Whole bunch of SR and IR Templates in a Management Pack - lets call it: "Company.Templates.MP" now what I want to do is edit this MP and add new List and String Properties to hold the responses provided from the
    Self Service Portal so that I can use a Runbook Activity to feed these responses into Orchestrator.
    Now what I have done is "Extended" the existing "Service Request" and "Incident" classes and created the new properties in each extended class. Now that I have Extended the default Classes I believe that the properties now apply
    to EVERY existing and new SR and IR.
    My question is... Do you think I have done this correctly?
    I have a gut feeling that I have done it wrong and I should revert my MP changes and then instead of extending the existing IR and SR Classes which affect all existing Work Items, I should create a new SR and IR class which would then be used to create new
    Templates which are then ONLY ones that contain the new properties that would be used for Runbook Automation.
    The feedback I receive will be VERY MUCHLY appreciated...

    Answering your implicit question in the title:
    Inherit is where you create a new class that has all the properties of the parent and then some new ones also, but people can still use the parent for regular work. This is for specialization, like say you want a new type of incident to
    cover firewall problems, and need new properties for the IP and Ports from the portal.
    Extended would be where you add properties to a class that make sense for all of those and all inheriting classes. say the client has a cost of IT tracking system where every Incident and Service Request needs to be assigned a cost of effort
    code, you would create two extensions for Incident and Service request, and point them at the same enum list. you wouldn't extend WorkItem, because changes, activities, released etc wouldn't use a simple cost estimate list value, and you wouldn't inherit off
    of SR and IR because all user requests should have this property, even if some of them are blank  
    New would be a class from scratch that inherits from Entity. This is hardly ever what you want to do, because even completely new things are either work items or config items, and should, where ever possible, inherit from one of those
    basil classes
    Now to your explicit question: No, i think you've done exactly what the situation called for. every SR should have this value, even if it is empty for the historical items.
    two side notes: 1) any item that refers to the base of an extension will continue to work as expected, but  2) Offerings are always the exception. The net of these two rule of thumb guidelines is that your existing templates should continue to work
    without modification, but you may have to recreate the offering before you can use the new property in a question.  
    AFAIK you cannot extend an abstract calls (ex. Work Item), but I could be wrong.
    http://codebeaver.blogspot.dk/

  • A question about inheritance and overwriting

    Hello,
    My question is a bit complicated, so let's first explain the situation with a little pseudo code:
    class A {...}
    class B extends A{...}
    class C extends B {...}
    class D extends C {...}
    class E extends B {...}
    class F {
      ArrayList objects; // contains only objects of classes A to E
      void updateObjects() {
        for(int i = 0; i < objects.size(); i++)
          A object = (A) objects.get(i); // A as superclass
         update(A);
      void update(A object) { ... }
      void update(B object) { ... }
      void update(D object) { ... }
    }My question now:
    For all objects in the objects list the update(? object) method is called. Is it now called with parameter class A each time because the object was casted to A before, or is Java looking for the best fitting routine depending on the objects real class?
    Regards,
    Kai

    Why extends is evil
    Improve your code by replacing concrete base classes with interfaces
    Summary
    Most good designers avoid implementation inheritance (the extends relationship) like the plague. As much as 80 percent of your code should be written entirely in terms of interfaces, not concrete base classes. The Gang of Four Design Patterns book, in fact, is largely about how to replace implementation inheritance with interface inheritance. This article describes why designers have such odd beliefs. (2,300 words; August 1, 2003)
    By Allen Holub
    http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html
    Reveal the magic behind subtype polymorphism
    Behold polymorphism from a type-oriented point of view
    http://www.javaworld.com/javaworld/jw-04-2001/jw-0413-polymorph_p.html
    Summary
    Java developers all too often associate the term polymorphism with an object's ability to magically execute correct method behavior at appropriate points in a program. That behavior is usually associated with overriding inherited class method implementations. However, a careful examination of polymorphism demystifies the magic and reveals that polymorphic behavior is best understood in terms of type, rather than as dependent on overriding implementation inheritance. That understanding allows developers to fully take advantage of polymorphism. (3,600 words) By Wm. Paul Rogers
    multiple inheritance and interfaces
    http://www.javaworld.com/javaqa/2002-07/02-qa-0719-multinheritance.html
    http://java.sun.com/docs/books/tutorial/java/interpack/interfaceDef.html
    http://www.artima.com/intv/abcs.html
    http://www.artima.com/designtechniques/interfaces.html
    http://www.javaworld.com/javaqa/2001-03/02-qa-0323-diamond_p.html
    http://csis.pace.edu/~bergin/patterns/multipleinheritance.html
    http://www.cs.rice.edu/~cork/teachjava/2002/notes/current/node48.html
    http://www.cyberdyne-object-sys.com/oofaq2/DynInh.htm
    http://www.gotw.ca/gotw/037.htm
    http://www.javajunkies.org/index.pl?lastnode_id=2826&node_id=2842
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=001588
    http://pbl.cc.gatech.edu/cs170/75
    Downcasting and run-time
    http://www.codeguru.com/java/tij/tij0083.shtml
    type identification
    Since you lose the specific type information via an upcast (moving up the inheritance hierarchy), it makes sense that to retrieve the type information ? that is, to move back down the inheritance hierarchy ? you use a downcast. However, you know an upcast is always safe; the base class cannot have a bigger interface than the derived class, therefore every message you send through the base class interface is guaranteed to be accepted. But with a downcast, you don?t really know that a shape (for example) is actually a circle. It could instead be a triangle or square or some other type.
    To solve this problem there must be some way to guarantee that a downcast is correct, so you won?t accidentally cast to the wrong type and then send a message that the object can?t accept. This would be quite unsafe.
    In some languages (like C++) you must perform a special operation in order to get a type-safe downcast, but in Java every cast is checked! So even though it looks like you?re just performing an ordinary parenthesized cast, at run time this cast is checked to ensure that it is in fact the type you think it is. If it isn?t, you get a ClassCastException. This act of checking types at run time is called run-time type identification (RTTI). The following example demonstrates the behavior of RTTI:
    //: RTTI.java
    // Downcasting & Run-Time Type
    // Identification (RTTI)
    import java.util.*;
    class Useful {
    public void f() {}
    public void g() {}
    class MoreUseful extends Useful {
    public void f() {}
    public void g() {}
    public void u() {}
    public void v() {}
    public void w() {}
    public class RTTI {
    public static void main(String[] args) {
    Useful[] x = {
    new Useful(),
    new MoreUseful()
    x[0].f();
    x[1].g();
    // Compile-time: method not found in Useful:
    //! x[1].u();
    ((MoreUseful)x[1]).u(); // Downcast/RTTI
    ((MoreUseful)x[0]).u(); // Exception thrown
    } ///:~
    As in the diagram, MoreUseful extends the interface of Useful. But since it?s inherited, it can also be upcast to a Useful. You can see this happening in the initialization of the array x in main( ). Since both objects in the array are of class Useful, you can send the f( ) and g( ) methods to both, and if you try to call u( ) (which exists only in MoreUseful) you?ll get a compile-time error message.
    If you want to access the extended interface of a MoreUseful object, you can try to downcast. If it?s the correct type, it will be successful. Otherwise, you?ll get a ClassCastException. You don?t need to write any special code for this exception, since it indicates a programmer error that could happen anywhere in a program.
    There?s more to RTTI than a simple cast. For example, there?s a way to see what type you?re dealing with before you try to downcast it. All of Chapter 11 is devoted to the study of different aspects of Java run-time type identification.
    One common principle used to determine when inheritence is being applied correctly is the Liskov Substitution Principle (LSP). This states that an instance of a subclass should be substitutible for an instance of the base class in all circumstances. If not, then it is generally inappropriate to use inheritence - or at least not without properly re-distributing responsibilities across your classes.
    Another common mistake with inheritence are definitions like Employee and Customer as subclasses of People (or whatever). In these cases, it is generally better to employ the Party-Roll pattern where a Person and an Organization or types of Party and a party can be associated with other entities via separate Role classes of which Employee and Customer are two examples.

  • Associations and extended objects

    Hi,
    I'm just beginning to look at bc4j so bear with me if I ask a stupid question :-)
    The thing is that I'm experimenting with simple inheritance and I cant seem to get the associations to work like I would expect. I have 3 classes (business components). Customer, Account (which in my model is an abstract superclass) and SavingsAccount. And there is an association between Account and Customer in my model implying of cause that there is an assosiation between all subclasses of Account (SavingsAccount) and Customer.
    Account and SavingsAccount are in seperate tables - mabye thats where my problems lie ?
    But no such associations are created automatically by the 'create database objects' command.
    Is this also the experience of others here ? What it means is that my model gets 'abused' when I create the associations and I'm not too happy about that.

    Well, then I'm stumped as to why that won't work for me. If I have the following code:
    import java.util.*;
    public class Test1
        private ArrayList<E extends Integer> aList;
        public Test1()
            aList = new ArrayList<Integer>();
        public void run()
            for (byte i = 0; i < 10; i++)
                Integer o = new Integer(i);
                aList.add(o);
        public ArrayList<E extends Integer> getResults()
            return aList;
    }I get "> expected".
    Your last piece of code shows what I will probably end up doing, as this just can't seem to work, i.e. getting each Object1 and casting it to an Object2.
    What I need, is to initially build an ArrayList containing Object1s. Then my Object2 class is an extension of Object1, and therefore I else want to have that ArrayList returned, but the info I need now are Object2s. So basically build an ArrayList of Object1s, needed in that particular class, make a method that returns it, invoke that method in another class, but have that ArrayList contain Object2s instead.
    While I could iterate through the elements, I will also need to return the ArrayList with Object2 elements in it from the other class, so I prefer being able to do it in one swoop, using generics, if at all possible. Which it seems not to be.
    Edited by: ThemePark on May 21, 2008 2:14 PM

  • Inheritance and byte-code...

    My coworker and I were having a discussion today that I imagine someone here will be able to resolve for us: we were talking about how wonderful inheritance is (when used properly, of course), and the issue of the compiled byte-code came up.
    Basically, it was my conclusion that a subclass contains only the byte code that differentiates it from the superclass; in other words, if a superclass is modified and recompiled, there is no need to recompile the subclass for the changes to take effect. My coworker disagreed, however, arguing that there would be linking problems between the two classes if the subclass was not recompiled (sign of an old assembly programmer, if you ask me).
    Anyone know the answer to this?

    I created a trivial Parent class and extended it with an
    even more trivial Child class. I compiled both classes
    and then made a change to the Parent class. After
    compiling the Parent class only, the change took effect
    in the Child class. This indicates that you are right and
    your co-worker is wrong. Here are the classes if you
    would like to show him.
    import java.awt.*;
    public class Parent
         Dimension d;
         Parent() {
              d = new Dimension(333, 777);
         public Dimension getDimension() { return d; }
    import java.awt.*;
    public class Child extends Parent
         Dimension d;
         public Child() {
              d = getDimension();
              System.out.println(d.height + " " + d.width);
         public static void main(String[] args) {
              new Child();
    }Mark

Maybe you are looking for

  • Problem-planned order start date in the past

    I use PP-PI - After MRP run, planned order was created and has exception message "06-start date in the past" its make me wonder because before this problem occur we already tested many time and never found this message(06). then i check in OPPR- fiel

  • Save function behaves like Save As

    In the last few months, some customers on Reader X have reported that when they go to save a form (both Acroform and XFA) they have filled in, using either File > Save or Ctrl-S or the Save icon, they are asked for a filename and a location - this is

  • Boot camp with Vista?

    can i run boot camp version 4.0.1 with Windows Vista Home Premium edition?  I used to have it until I replaced my hard drive and upgraded to Lion.  Now it seems that only Windows 7 will work and I'll have to buy that OS.

  • ME2K Report Failed to Include New SRM PO Replicated ECC

    We implemented SRM 7.0 in July 2011 and we noticed that when run ME2K (RM06K00 program) the generated report is only listing ECC POs only. Why New SRM PO replicated in ECC is not  inlcuded? The reprot should include all PO types in ECC. We also notic

  • Compositing in KDE with intel 2.6

    Ive just installed a fresh system with kdemod and latest xorg/intel. But I cant enable compoisiting in kde when using kwin, ive tried enable compositing via xorg.conf, having the only thing in there being load composite extenstion. Im using modesetti