Inheritance questions

Say a superclass has 3 methods and 3 properties. NExt, I create a subclass which overrides these same 3 methods and properties. Either way, my question really is this... When casting up and down, when it is a subclass and a super class reference, are the properties preserved when it is cast(implicitly) up to a superclass reference, so that, in case it needs to be cast back down (explicitly) to its original subclass form, the subclass properties can still be referred to? Are the original variables still preserved (much like a static variable)?

are the properties preserved when it is cast(implicitly) up to
a superclass reference, so that, in case it needs to be cast backAn object instance does not change when it's casted into a superclass reference. This means it can be casted back (if this weren't the case, then all methods that return Object would be pretty useless).
In addition, accessing an object method via a superclass reference does not mean that you'll invoke a superclass method. Instead, it invokes the method appropriate to the object (otherwise overriding and polymorphism would be pretty useless).
However, accessing an object's instance variable via a superclass reference does access the superclass variable, not the subclass variable.
I would suggest playing with this for a while ... here's something to start with:
public class DROCPDP
    public static void main( String argv[] )
    throws Exception
        Base a = new Base();
        Sub b = new Sub();
        Base c = (Base)b;
        Sub d = (Sub)c;
        System.out.println("\nOperations on A:");
        System.out.println("a.var = " + a.var);
        a.method();
        System.out.println("\nOperations on B:");
        System.out.println("b.var = " + b.var);
        b.method();
        System.out.println("\nOperations on C:");
        System.out.println("c.var = " + c.var);
        c.method();
        System.out.println("\nOperations on D:");
        System.out.println("d.var = " + d.var);
        d.method();       
    private static class Base
        public String var = "Base";
        public void method()
            System.out.println("Called Base.method; variable = " + var);
    private static class Sub extends Base
        public String var = "Sub";
        public void method()
            System.out.println("Called Sub.method; variable = " + var);
}

Similar Messages

  • Constructor Inheritance Question

    Here's a quote from the Java Tutorials at http://java.sun.com/docs/books/tutorial/java/javaOO/objectcreation.html :
    "All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program."
    In order to fully understand this concept, I created two classes: a ClassParent and a ClassChild.
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
    public class ClassChild extends ClassParent
        public static void main(String[] args) {
            ClassChild child = new ClassChild();
    }Both classes compiled successfully, which raised the following question:
    I understand that the ClassParent default constructor calls the Object's no-argument constructor.
    Does the ClassChild also call the Object's constructor once it realizes that the ClassParent does not have a no-argument constructor?
    And a somewhat non-related question:
    Seeing how ClassParent calls Object's no-argument constructor if it does not have one of its own, does it also extend the Object class?
    Edit: After running the following code, I realized that the answer to my last question is yes:
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
           boolean test = tester instanceof Object;
           System.out.println(test);
    }Edited by: youmefriend722 on May 26, 2008 1:54 PM

    youmefriend722 wrote:
    I think I'm getting a basic grasp now but want to make sure that I'm not misunderstanding anything.
    Constructor inheritance:
    If a no-argument constructor is invoked but one isn't declared in that class, the superclass's no-argument constructor will be invoked. Well, sort of. If you invoke a constructor that doesn't exist, you get an error. Keep in mind that the invocation and the constructor may both be automatically supplied by the compiler, and that the compiler won't automatically create a no-arg constructor for a class if you define any constructors for that class.
    So if you don't define any constructors in a class, then a no-arg one is created automatically (at compile time) and (at runtime) when you instantiate that class, that no-arg constructor will try to invoke the superclass's no-arg constructor.
    But suppose you do define a constructor, one that takes an argument. Then if you try to invoke a no-arg constructor on that class, you'll get an error, and the superclass's no-arg constructor won't be invoked (because the error happens first).
    If the superclass does not have a constructor, then the superclass's superclass's constructor will be invoked.No. That never happens. Every class has a constructor (although it might have permissions which make it inaccessible, which is a whole other issue we'll worry about later).
    If the superclass does have a constructor but doesn't have a no-argument constructor, then there will be a compile-time error.Only if you try to invoke the no-arg constructor, which might happen implicitly. For example, if you write a superclass with a 2-arg constructor, and you write a subclass with a 1-arg constructor, and the 1-arg subclass's constructor invokes the superclass's 2-arg constructor, then there's no problem, even though in this example, the superclass doesn't have a no-arg constructor.
    Constructors in general:
    In every constructor, the superclass's no-argument constructor will be invoked if the none of the superclass's constructors are explicitly invoked.Yeah, I think that's right.

  • Multiple inheritance question

    This just occurred to me. I read the other day that all classes inherit Object. So if I have a class defined as public class A {
    }and I call toString() on an instance of this class, I get Objects toString implementation (assuming it has not been overridden). OK, this I understand.
    Now if instead I havepublic class A extends B {
    }and I call toString() on A, assuming it is not overridden in either A or B, I will still get Objects toString method. My question is, does A still extend Object, or does it inherit the fact that B extends Object? And what happens if I override toString() in B - what will I get if i call toString on an instance of A?

    java.lang.Object is at the root of all class inheritance hierarchies in Java. Therefore, all classes inherit from java.lang.Object, either directly or indirectly.
    When you call a method on an object of class Foo, Foo's inheritance hierarchy is traced starting with Foo and going all the way back to java.lang.Object, looking for an implementation of the method. The first implementation encountered is the one that gets used. So in your example calling toString on an instance of class A will result in B's toString method being executed.
    Hope this makes sense.

  • For loops & inheritance question

    I am trying this exercise dealing w/inheritance. I enter at command line a random number of c's, s's and m's. for checking,savings and money market. I then parse the string and check for the character. From there I create one of the accounts. then I am supposed to make a report that displays the past 3 months activities. the first account created gets 500 deposit the from there each account after the first gets an additional 400. so it would be: 500,900,1300,etc. Here is what I have so far, but the report part is where I can't figure out exactly how to go about solving it. Thanks in advance.
    public static void main( String args[] ){
         int intDeposit = 500;
         char charTest;
         Object [] objArray = new Object[args[0].length()];
         for ( int j = 0; j < 3; j ++ ){                        System.out.println( "Month " + ( j +1 ) + ":" );
             for( int i = 0; i < args[ 0 ].length(); i ++ ){
              charTest = args[ 0 ].charAt( i );
                         if (charTest == 'c' ){
                  BankAccount at = new  CheckingAccount( intDeposit );
                  objArray=at;
              else if( charTest == 's' ){
              BankAccount at = new SavingsAccount( intDeposit );
              objArray[i]=at;
              else if( charTest == 'm' ){
              BankAccount at = new MoneyMarket( intDeposit );
              objArray[i]=at;
              else{
              System.out.println( "invalid input" );
              }//else
              intDeposit += 400;
              System.out.println();
         }//for j
         for (int counter = 0; counter < objArray.length; counter ++ ){
              System.out.println( "Account Type: " +
                        objArray[counter].toString() );
              System.out.println( "Initial Balance: " +
                        (BankAccount) objArray[counter].getCurrentBalance() );
         System.out.println( "TotalDeposits: " + objArray[counter].getTotalDeposits() );
         System.out.println();
         }//for i
    }//main
    }//TestBankAccount.java\

    The only thing I think is wrong is the following line:
    System.out.println( "Initial Balance: " +                    (BankAccount) objArray[counter].getCurrentBalance() );
    Should be:
    System.out.println( "Initial Balance: " +                    ((BankAccount) objArray[counter]).getCurrentBalance() );

  • Small inheritance question

    Got a small quesiton about inheritance.
    I have a 'User' Class and extending that class is 'Player' and 'Enemy'.
    Player class and Enemy class contains extra stuff like different image and moves different.
    When I create a new player do I create an instance of the 'User' class or the 'Player' class?
    Also,
    If values change in the 'Player' class do the values also change in te 'User' class?
    I am fairly new to java.
    Thanks

    MarcLeslie120 wrote:
    Got a small quesiton about inheritance.
    I have a 'User' Class and extending that class is 'Player' and 'Enemy'.Sounds odd. Aren't some players also your enemy? Or is Player me, and everybody else is Enemy?
    Player class and Enemy class contains extra stuff like different image and moves different.Okay. If it's just different, that's one thing. If it's adding extra methods, you probably don't want to inherit.
    When I create a new player do I create an instance of the 'User' class or the 'Player' class?If it's going to be a Player, you need to create a Player.
    If values change in the 'Player' class do the values also change in te 'User' class?If you mean an instance variable (a non-static member variable), then there aren't two separate objects. There's just one object, that is both a Player and a User. The variable exists only once.
    Your inheritance hierarchy smells funny, but without more details about what these classes represent and what you're trying to accomplish, it's hard to provide concrete advice.

  • [Solved] C++ inheritance question

    I have a base class and a bunch of inherited classes.
    I am doing something like this in the main.
    baseclass* base[2];
    base[0]= new _derived1("hello");
    base[1]= new _derived2("world");
    How do I code my base class or what-ever-else so that I CAN'T do this:
    baseclass* base2;
    base2 = new baseclass("class");
    The base class has 1 constructor with an argument type string. I can't have a default constructor.
    So in short. I can create a particular derived class, like a derived1, but can't create a plain base class. (it should throw a compilation error)
    Any help would be appreciated.
    Thanks.
    Last edited by lamdacore (2011-02-06 00:38:43)

    Oh I want a compile error when I do this:
    baseclass* base2;
    base2 = new baseclass("class");
    Example code. So I don't want the base class to be able to make a Base type object. As soon as I do that it SHOULD throw a compilation error.
    class Base{
    public:
    Base(string st):m_st(st)
    virtual ~Base(){
    virtual string ann() const{
    return "";
    virtual string bnn() const{
    return m_st;
    virtual string cnn(string msg) const{
    string k="hey ";
    k.append(msg);
    return k;
    private:
    string m_st;
    class derived1:public Base{
    public:
    derived1(string st):Base(st){
    virtual ~derived1(){
    cout<<"kill";
    virtual string ann() const{
    return "hullo";
    virtual string bnn() const{
    return Base::bnn();
    virtual string cnn(string msg) const{
    string k="hey ";
    k.append(msg);
    return k;
    private:
    string m_st;
    Last edited by lamdacore (2011-02-06 23:38:23)

  • Inheritance question

    I'm working on an assignment but I'm getting the following error when I test the code:
    "Card.java": Error #: 300 : constructor CraftItem() not found in class questiontester.CraftItem at line 3, column 8
    I've already tried a number of things to resolve the issue but it keeps cropping up. Can anyone shed any light on what I'm doing wrong please?
    Here's my code:
    CraftItem.java
    (I know this works because it tested out okay)
    package questiontester;
    public class CraftItem {
    // instance variables
    public String itemCode;
    public double price;
    // constructor
    public CraftItem(String itemCodeValue, double itemPriceValue){
    itemCode = itemCodeValue;
    price = itemPriceValue;
    // getter for itemCode
    public String getItemCode() {
    return itemCode;
    // getter for price
    public double getPrice() {
    return price;
    // setter for itemCode
    public void setItemCode(String itemCodeValue) {
    itemCode = itemCodeValue;
    // setter for price
    public void setPrice(double itemPriceValue) {
    price = itemPriceValue;
    // toString() value
    public String toString() {
    return "Item code is " + itemCode + " and costs " + price + " pounds.";
    Card.java
    (this class extends CraftItem and is where I'm getting the error. The error message highlights the class bit in italics as being the problem)
    package questiontester;
    public class Card extends CraftItem {
    // instance variables
    private String cardType;
    private String cardSize;
    //private String itemCode;
    //private double price;
    // Constructor
    public void Card(String cardTypeValue, String cardSizeValue,
    String itemCodeValue, double itemPriceValue) {
    cardType = cardTypeValue;
    cardSize = cardSizeValue;
    itemCode = super.getItemCode();
    price = super.getPrice();
    // methods
    Test.java
    (this the code I'm using to test functionality - it normally works just fine but the error message cropped up when I tried to extend CraftItem with Card)
    package questiontester;
    public class Test {
    public static void main(String args[]) {
    // creating a new object instance with default values
    // values 123456 and 1.5 could also have been set here
    CraftItem defaultItem = new CraftItem("000000",0.0);
    // calling the toString() method to display the text
    // this should display defaultItem with its initial values
    System.out.println(defaultItem.toString());
    // setting the item code to 123456
    // this overrides the initial String value of defaultItem
    defaultItem.setItemCode("123456");
    // setting the price to 1.5
    // this overrides the initial double value of defaultItem
    defaultItem.setPrice(1.5);
    // calling the toString() method to display the text
    // this should now show defaultItem with its new values
    System.out.println(defaultItem.toString());
    // test to check whether getter methods work
    System.out.println(defaultItem.getItemCode());
    System.out.println(defaultItem.getPrice());
    // test to see that setters work for additional items
    CraftItem anotherItem = new CraftItem("000000",0.0);
    anotherItem.setItemCode("345345");
    anotherItem.setPrice(0.5);
    System.out.println(anotherItem.toString());
    As I say, I'm not sure how to resolve the Error#: 300 so any advice on how to do this would be greatly appreciated.
    Cheers - Nic

    Here's my updated code - I'll repost the Test and CraftItem code too:
    Card.java
    package questiontester;
    public class Card extends CraftItem {
      // instance variables
      private String cardType;
      private String cardSize;
      private String itemCode;
      private double price;
      // Constructor
      public Card(String cardTypeValue, String cardSizeValue) {
            super(itemCodeValue, itemPriceValue);
            cardType = cardTypeValue;
            cardSize = cardSizeValue;
    // methods
    CraftItem.java
    package questiontester;
    public class CraftItem {
      // instance variables
      public String itemCode;
      public double price;
      // constructor
      public CraftItem(String itemCodeValue, double itemPriceValue){
        itemCode = itemCodeValue;
        price = itemPriceValue;
      // getter for itemCode
      public String getItemCode() {
        return itemCode;
      // getter for price
      public double getPrice() {
        return price;
      // setter for itemCode
      public void setItemCode(String itemCodeValue) {
        itemCode = itemCodeValue;
      // setter for price
      public void setPrice(double itemPriceValue) {
        price = itemPriceValue;
      // toString() value
      public String toString() {
        return "Item code is " + itemCode + " and costs " + price + " pounds.";
    Test.java
    package questiontester;
    public class Test {
      public static void main(String args[]) {
        // creating a new object instance with default values
        // values 123456 and 1.5 could also have been set here
        CraftItem defaultItem = new CraftItem("000000",0.0);
        // calling the toString() method to display the text
        // this should display defaultItem with its initial values
        System.out.println(defaultItem.toString());
        // setting the item code to 123456
        // this overrides the initial String value of defaultItem
        defaultItem.setItemCode("123456");
        // setting the price to 1.5
        // this overrides the initial double value of defaultItem
        defaultItem.setPrice(1.5);
        // calling the toString() method to display the text
        // this should now show defaultItem with its new values
        System.out.println(defaultItem.toString());
        // test to check whether getter methods work
        System.out.println(defaultItem.getItemCode());
        System.out.println(defaultItem.getPrice());
        // test to see that setters work for additional items
        CraftItem anotherItem = new CraftItem("000000",0.0);
        anotherItem.setItemCode("345345");
        anotherItem.setPrice(0.5);
        System.out.println(anotherItem.toString());
    Update
    I've removed the void and the original error#: 300 message has gone, replaced by the following two:
    "Card.java": Error #: 300 : variable itemCodeValue not found in class questiontester.Card at line 14, column 15
    "Card.java": Error #: 300 : variable itemPriceValue not found in class questiontester.Card at line 14, column 30

  • Inheritance Question part 2

    class ClassA
    public void sayHelloInA() { System.out.println("Hello in class A"); }
    public void show() { System.out.println("Show in ClassA"); }
    class ClassB extends ClassA
    public void sayHelloInB() { System.out.println("Hello in class B"); }
    public void show() { System.out.println("Show in ClassB"); }
    public class Test
    public static void main(String[] args)
    ClassA c = new ClassB();
    c.sayHelloInB();
    c.show();
    Why c.sayHelloInB() does not compile but c.show() compiles and runs (which displays "Show in ClassB")

    Russell53 wrote:
    Why c.sayHelloInB() does not compile but c.show() compiles and runs (which displays "Show in ClassB")The answer was already posted in your [previous thread|http://forums.sun.com/thread.jspa?threadID=5372352]. Please continue the discussion there.

  • Another Inheritance Question, please help.

    Below is a setup of two packages and three classes:
    package com.foo.package1
    * This is the main superclass.
    public class SuperClass extends Object {
        public SuperClass () {
        protected getFoo() {
            return "foo";
    }here is the second package:
    package com.foo.package2
    import com.foo.package1.SuperClass;
    * This class extends SuperClass. Obviously, I removed
    * all methods for brevity.
    public class SubClass extends SuperClass {
        public SubClass () {
            super();
    * This class extends SubClass. A method here is supposed to
    * create an instance of the SuperClass and call a method on it.
    * In this case, {SuperClass#getFoo()} is called.
    public class SubSubClass extends SubClass {
        public SubSubClass () {
            super();
        public void method() {
            SubClass sc = new SubClass();
            System.out.println (
                    sc.getFoo());
    }Now why do I get a compile exception "getFoo() has protected access in com.foo.package1.SuperClass"? Should that be the case?
    Thanks in advance.
    Georg.

    It isn't a bug. Saying that protected members of a class are accessible from subclasses is not exactly true.
    From the JLS: 6.6.2 Details on protected Access
    A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
    SubSubClass is not responsible for the implementation of SuperClass. So basically, a class can only have access to protected members defined in a superclass if either:
    a) it is in the same package
    - or -
    b) the type of the reference used to access those members is that class, or one of it's subclasses.

  • Newbie inheritance question

    I have created a base class which implements cloneable (and I know the clone function works). I have also created two classes derived from the base class (which don't have cloneable implemented).
    Is it possible to "clone" the base class components of both derived classes. Here is what I mean
    //both derived from class1 which implements clone()
    class2 c2
    class3 c3
    c2 = c3.clone(); //I just want to clone the c1 member variables
    How do you go about doing this correctly.

    You won't be able to do c2 = c3.clone(), because c3.clone() will return a reference to an instance of class3, which is not a subclass of class2.
    The correct first step of the clone() method is to call super.clone(), which will give you an instance of the same class as the object you're cloning, with all the fields set to the same values. You can then change some fields' values before returning the result.

  • An inheritance question

    How would I go about accessing a private instance variable in a super-class from a sub-class? I'm thinking it either has to do with using the .super keyword or creating a method in the super-class which would return the value. Could someone help me with this?

    Hi,
    Private members cannot be accessed outside the class in which it is defined, NOT EVEN IN CHILD CLASS.
    However, you can create an accessor method like
    public String getString()
    ..........and this method can be used from the child class.

  • Jframe inheritance question

    hi why is it when i set the variable inside secondframe class
    it just doesn't stick. i have a example that describes my problem better.
    i can see that when void show is called that it makes a new instance of
    second frame class so how would i fix this.
    i know i could scope int x through the show method and use it that way
    but im wanting to change varibles inside second class dynamicly
    any ideas thanks
    firstclass with frame1
    public class Main {
        public static void main(String[] args) {
              firstframe frame = new firstframe();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(270, 500);
              frame.setVisible(true);
            frame.setAlwaysOnTop(true);
    class firstframe extends JFrame
        private int x = 10;
        firstframe(){
        super.setTitle("first frame");
        System.out.println("first result :" + x);
        secondframe frame2 = new secondframe();
        secondclass.show();
    }second class
    public class secondclass {
        public static void show()
              secondframe frame = new secondframe();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(270, 500)thanks;
              frame.setVisible(true);
            frame.setAlwaysOnTop(true);
    class secondframe extends JFrame
        private int x;
        public secondframe(){
            super.setTitle("second frame");
            System.out.println("end result :" + x);
        public void setvaribles(int x){
            this.x = x;
    }

    Use proper Java naming conventions.
    Class names should be upper cased: ie FirstFrame, not firstframe.
    Method names are also upper cased except the first word: ie. setVariables, not setvariables.
    Why is show a static method? The only static method should be the main(...) method.
    You don't even need a show() method, the code to create the frame should be in the constructor.
    Also, applications should only have a single JFrame. Other windows should be JDialogs.

  • HELP: Inheritance question: Overriding a method.

    Hi all.
    I have one class: BatchJob.java which defines the following method:
    (1) protected void handleException(Exception e) {
         setInitError( true );
         printTrace(getClass().getName(), "*** ERROR: " + e.toString());
         createMailError(e);
    Another class JBDCBatchJob.java which extends BatchJob, overrides the previous method like this:
    (2) protected void handleException(SQLException sqlEx) {
         setInitError( true );
         printTrace(getClass().getName(), getSqlQuery(), sqlEx);
         createMailError(getSqlQuery(), sqlEx);
    where getSqlQuery() is a getter for a String member field which contains the last SQL query sent to the JDBC Driver.
    In another class (say SimpleJDBCBatchJob) which extends JDBCBatchJob, I've got the following code fragment:
    try {
    // statements that may throw SQLException or in general Exception
    catch (Exception e) {
    handleException( e );
    I have realized that the method invoked by the JVM when an SQLException is thrown in SimpleJDBCBatchJob is (1), that is, the "handleException" defined in BatchJob and not that in JDBCBatchJob which it should (or at least, that's what I meant). Why is it? Is it possible to accomplish this without having to rename the method (2), I mean, using method overriding? Any idea would be highly appreciated. THANKS in advance.

    You didn't override the method handleException in JBDCBatchJob, you just overloaded it. So int JBDCBatchJob, you actually had two versions of handleException, one that took a parameter of the type Exception, one that took a parameter of the type SQLException.
    So, in SimpleJDBCBatchJob, you need to have a catch block like
    try {
    // statements that may throw SQLException or in general Exception
    catch (SQLException sqle) {
    handleException( sqle );
    catch (Exception e) {
    handleException( e );
    This would call your handleException in BatchJob if a general exception was thrown, and the handleException in JBDCBatchJob if a SQLException was thrown from the try block.
    Hope that makes things clearer for you.
    Alan

  • JButton, JMenuItem, & Action

    I have an inheritance question regarding the relationships between these objects.
    Basically, I would like to have a generic actionPerformed() method for objects inside an Action object, but I want a little more customization whenever the action is represented as a button.
    For example, if my action is a JButton, I would like there to be two states, whereas I only want one state in my JMenuItem. Here is what I have right now for two seperate classes that implement (generally) the same functionality.
    class MyButton extends JButton implements ActionListener {
      public MyButton(String name) {
        super(name);
        setBackground(Color.RED);
        addActionListener(this);
      public void actionPerformed(ActionEvent e) {
        if(getBackground() == Color.RED) {
          setBackground(Color.GREEN);
          // Perform State 1 operations.
        } else {
          setBackground(Color.RED);
          // Perform State 2 operations.
    class MyMenuItem extends JMenuItem implements ActionListener {
      public MyMenuItem(String name) {
        super(name);
        addActionListener(this);
      public void actionPerformed(ActionEvent e) {
        // Perform State 1 operations.
    }Is there a good way to represent one Action object for these two implementations? Thanks for the help.

    here is what I would do...
    move the actionPerformed method to its one class and handle it differently, it might look like this...
    class MyButton extends JButton {
      public MyButton(String name) {
        super(name);
        setBackground(Color.RED);
    public class MyListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
        if(e.getSource().getBackground() == Color.RED) {
          e.getSource()setBackground(Color.GREEN);
          // Perform State 1 operations.
        } else {
          e.getSource().setBackground(Color.RED);
          // Perform State 2 operations.
    class MyMenuItem extends JMenuItem {
      public MyMenuItem(String name) {
        super(name);
    public static void main(String[] args) {
      MyListener color = new MyListener();
      MyMenuItem item = new MyMenuItem("name");
       item.addActionListener(color);
       MyButton button = new MyButton("button");
       button.addActionListener(color);
    }This way you have one listener instance for your button. you'll have to do some work in the actionListener to identify the source of the event, but you should be able to figure that out on your own. The 'code' I posted is untested, but you should get the idea.

  • Implementing OOP inheritance in T-SQL (not an O/R question)

    Is it possible to cleanly obtain the inheritance benefit of object-oriented programming in T-SQL? 
    This is not about O/R mapping, which has been discussed to death all over the web, but rather specifically about implementing a form of inheritance in T-SQL.
    Here’s why I would ask such an insane question: 
    I maintain a large body of existing T-SQL that implements logic that has to be tightly tied to the database. 
    It’s not heavily declarative (i.e., does not rely heavily on large monolithic SQL statements and set manipulations), because the operations that have to be carried out are by their nature sequential. 
    (And imperative code can be tested in bite-size pieces, whereas huge, tight, brittle declarative SQL is difficult to maintain.) 
    And I can’t rewrite it.
    I’m now faced with the prospect of implementing new functionality, which will have the effect of introducing slight variations across the current
    functionality.  An obvious way to implement this would be with tests and branches in every place where the functionality has to vary. 
    This would spread the new functionality across the existing code in a rather unstructured way, making maintenance difficult. 
    At the other extreme, I could clone the entire codebase, and make the alterations in the cloned code for the new functionality. 
    At run-time, you would call into the correct code.  This would cause incredible code bloat and the attendant maintenance headaches.
    Inheritance and virtual functions would solve this nicely: the common code would be placed in one class, and the parts that vary in two
    other separate classes.  Alas, T-SQL does not implement inheritance.
    There is a third way: 
    implement virtual functions by hand in T-SQL.  At virtual function call sites, you would simply employ a lookup to determine the correct virtual function, and then call it dynamically.
     This could be easily expanded to handle a third set of logic and so on. 
    It would only require modifying the entire codebase once, to insert the virtual function call points. 
    The vtable of virtual functions could be stored as a table in SQL Server. 
    But this sounds like an awful thing to do to future maintainers.
    Has anyone else faced this situation, and how did you address it?  Does anyone know of any other approach that would mimic inheritance
    in T-SQL and/or avoid the uglinesses of the above?  Thanks.

    There is a third way: 
    implement virtual functions by hand in T-SQL.  At virtual function call sites, you would simply employ a lookup to determine the correct virtual function, and then call it dynamically.
    That can be done with
    dynamic SQL.
    However, there is always the ever-present performance requirement with database queries. So a fancy implementation can quickly collapse to plain in-line code stored procedure with performance benefits.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Maybe you are looking for

  • ITunes 10.6.3 and iPhone 5.1 - firmware file???

    I am trying to find my "Personal Hot Spot" on my iPhone 4 so that I can use my new iPad through my personal hot spot.  First of all my iPhone is still on version 4 so I was told to update to version 5.1.  I was also told to update my iTunes to versio

  • DV6 1130SA Upgrades

    I have downloaded the service manual for my laptop (DV6 1130SA) and have been looking at the processors. Currently it has an Intel Dual Core T4200 800 FSB but listed are a few of the Core 2 Duo processors. So I have been thinking on getting a new pro

  • Connecting to 9i Lite DBMS via SQL*Plus?

    Finally got the install to run successfully. However, I can't make an ODBC connection to the database with SQL*Plus. Any ideas (other than going back to 8i Lite)?

  • Stacks: fan option is missing

    Hi, The option to open stacks in a fan is missing. When I control-click on a stack to open the preferences, the "view contents" pane shows three options: grid, list, and automatic; there is no fan option. The grid and automatic options seem to be the

  • Serialize DOM between two ejb's performance

    Hi, I am working with XML in a ejb container and I used JDOM Document (org.jdom.Document) to send the xml document between two ejb's, I picked JDOM because the Document implements the Serilizable interface. Then I did some performance tests on sendin