Jose Sandoval Google
 Resume     Book     Software     Drawings     Home     Subscribe to RSS feed Search Web Search josesandoval.com

Java inheritance
Thursday, October 21, 2004

Inheritance, together with encapsulation, and polymorphism are the
pillars of Object Oriented Theory.

Java is an Object Oriented programming language. Some purists debate
it's OOness, as it doesn't treat int, char, boolean, and byte as
objects. However, Java is an OO language whether we like it or not.

Java has the notion of protected members, which are only available to
to extending classes and class which reside in the same package as the
"protecting" class.

Now, if I wanted to get access to those protected members outside of
the package and would prefer not to use multiple levels of
inheritance, how do I get access to those members?

For example:
1. Let say, you have a class with protected fields and methods in ClassA.

2. Let say, you have your working class (ClassB), which is already
extending one super class (Java has single inheritance, after all).
Now, you need some functionality from ClassA. How do you get that
functionality? Without layering your inheritance chain and growing
your object without reason?

One solution:
Extend the classA and have provide accessor methods to get to the
protected members of ClassA, then use composition, rather than
inheritance.

Now you have all that code available everywhere and anywhere.

A quick example:


class SuperClass {
public superValue = 42;
}

class WithProtection {
private int toReturn = 666;
protected static final String PROTECTED_KEY = "PROTECTED_KEY";
protected int protectedInt() {
return 666;
}
}

class WorkingClass extend SuperClass {
public static void main(String[] args) {
System.out.println("superValue = " + superValue);

// I want WithProtection's funcationality. How do I do that?
// Without creating an unnecessary chain of inheritance.
// Se below for WrapperClass code
WrapperClass wrapperClass = new WrapperClass();
System.out.println("WithProtection.PROTECTED_KEY = "
+ wrapperClass.getKey());
System.out.println("WithProtection.protectedInt() = "
+ wrapperClass.getProtectedIntMethod();
}
}

class WrapperClass extend WithProtection {
public String getKey() {
// This field is available
return PROTECTED_KEY;
}

public int getProtectedIntMethod() {
// This method is available also
return protectedInt();
}
}


The output:
  superValue = 42
  WithProtection.PROTECTED_KEY = PROTECTED_KEY
  WithProtection.protectedInt() = 666

Cool, ah?


7:30 PM | 0 comment(s) |

Comments:


This page is powered by Blogger. Isn't yours?

Guestbook
© Jose Sandoval 2004-2009 jose@josesandoval.com