Language Agnostic Basic Programming Question - language-agnostic

This is very basic question from programming point of view but as I am in learning phase, I thought I would better ask this question rather than having a misunderstanding or narrow knowledge about the topic.
So do excuse me if somehow I mess it up.
Question:
Let's say I have class A,B,C and D now class A has some piece of code which I need to have in class B,C and D so I am extending class A in class B, class C, and class D
Now how can I access the function of class A in other classes, do I need to create an object of class A and than access the function of class A or as am extending A in other classes than I can internally call the function using this parameter.
If possible I would really appreciate if someone can explain this concept with code sample explaining how the logic flows.
Note
Example in Java, PHP and .Net would be appreciated.

Let's forget about C and D because they are the same as B. If class B extends class A, then objects of type B are also objects of type A. Whenever you create an object of type B you are also creating an object of type A. It should have access to all of the methods and data in A (except those marked as private, if your language supports access modifiers) and they can be referred to directly. If B overrides some functionality of A, then usually the language provides a facility to call the base class implementation (base.Foo() or some such).
Inheritance Example: C#
public class A
{
public void Foo() { }
public virtual void Baz() { }
}
public class B : A // B extends A
{
public void Bar()
{
this.Foo(); // Foo comes from A
}
public override void Baz() // a new Baz
{
base.Baz(); // A's Baz
this.Bar(); // more stuff
}
}
If, on the other hand, you have used composition instead of inheritance and B contains an instance of A as a class variable, then you would need to create an object of A and reference it's (public) functionality through that instance.
Composition Example: C#
public class B // use A from above
{
private A MyA { get; set; }
public B()
{
this.MyA = new A();
}
public void Bar()
{
this.MyA.Foo(); // call MyA's Foo()
}
}

depending on the access level (would be protected or public in .NET), you can use something like:
base.method(argumentlist);
the base keyword in my example is specific to C#
there is no need for an instance of class A, because you already have a class A inherited instance

Basically you need a reference to the parent class.
In PHP:
parent::example();
From: http://www.php.net/manual/en/keyword.parent.php
<?php
class A {
function example() {
echo "I am A::example() and provide basic functionality.<br />\n";
}
}
class B extends A {
function example() {
echo "I am B::example() and provide additional functionality.<br />\n";
parent::example();
}
}
$b = new B;
// This will call B::example(), which will in turn call A::example().
$b->example();
?>

I find that the best way to tame the complexity of inheritance is to ensure that I only make B inherit from A when it really is a specialization of the superclass. At that point, I can call A's methods from inside B just as if they were B's own methods, and if B has overridden them then I can only suppose that this must be for a good reason.
Of course, quite often it is useful for B's implementation of a method to invoke A's implementation on the same object, generally because the subclass is wrapping extra behavior around the superclass's basic definition. The way in which you do this varies between languages; for example, in Java you do this:
super.methodName(arg1, ...);

Here's a quick Java example:
public class Aclass
{
public static void list_examples()
{
return("A + B = C");
}
}
public class Bclass extends Aclass
{
public static void main(String [] args)
{
System.out.println("Example of inheritance "+list_examples);
}
}
Note that the method for accessing the parent class shouldn't change. Because you are extending you shouldn't have to say parent:: or anything unless you are overriding the parent method / function.

It seems to me that extending your class might not be your best option. Class "B", "C", and "D" should only extend class "A" if they are truly an extension of that class, not just to access some method. For instance "Huffy" should not extend "BrandNames" just because "Huffy" is a brand name and you want access to one of the methods of "BrandNames". "Huffy" should instead extend "Bicycle" and implement an interface so the methods of "BrandNames" can be used. An additional benefit here is that (in Java) multiple interfaces can be used but a class can only be extended once. If in your example class "B"' needed to access a method from class "A" that could work, but if class "C" needed to access a method from class "A" and class "'B"' then you would have to use an interface in class "'C".

Related

How to check that a List contains only certain unrelated class types using junit's assertThat?

Would appreciate some help with hamcrest and junit matchers... :)
I'm using junit-4.11.jar and hamcrest-core-1.3.jar on Eclipse Kepler with sun's jdk 1.6.0_30.
I have a class that holds an instance of any unknown type like so:
class UnknownClassHolder {
private Class<?> clazz;
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
}
clazz can be any class.
I want to my junit test to be something like this:
class UnknownClassHolderTest {
#Test
public void test() {
ArrayList<UnknownClassHolder> list = new ArrayList<UnknownClassHolder>();
UnknownClassHolder x = new UnknownClassHolder();
//lets add an Integer
x.setClazz(Integer.class);
list.add(x);
UnknownClassHolder y = new UnknownClassHolder();
//lets add a vector
y.setClazz(Vector.class);
list.add(y);
//now check that we added an Integer or a Vector using assertThat
for (UnknownClassHolder u: list) {
assertThat(u.getClazz(), anyOf(isA(Integer.class), isA(Vector.class))));
}
}
}
Junit's assertThat doesn't like this. It doesn't compile due to Integer & Vector Types not being related to each other via sub/super classes:
The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Class<capture#1-of ?>, AnyOf<Vector>)
Is there a more succinct way to do this other than:
assertThat(u.getClazz().getName(), either(is(Integer.class.getName())).or(is(Vector.class.getName())));
Is there a particular reason for using Matcher<? super T> rather than Matcher<?> in the org.hamcrest.MatcherAssert.assertThat(...) method?
Thanks.
First, you should be using is instead of isA since you're asserting that one class equals another. isA is for testing that an object is an instance of some class. Second, the only thing I can make work is forcing the compiler to see these as raw Objects.
assertThat(u.getClazz(), anyOf(is((Object) Integer.class), is((Object) Vector.class)));

hi.using super in extending

my code is like this
public class B {
public B(int f) {
}
}
public class A extends B{
int f=4;
public A() {
super(f);
}
}
why does it make a compile error?
In order to create an instance of class A, Java will behave as if it first creates an instance of B, meaning that the constructor of the super class, super(), will be called, (or in this case, you call it yourself) and then "adding on" the attributes of class A.
This is also why a super() call always has to be the first instruction in a constructor.
You are trying to pass an argument, which in a sense doesn't exist yet, because you try to read f before you called super().
What you could do is the following:
public class A extends B {
static final int F_CONST = 4;
int f = F_CONST;
public A() {
super(F_CONST);
}
}
Here F_CONST is a constant "static" variable, which is a "class variable", instead of an "object or instance variable". static members will be initialized when the class is loaded in memory, which is before any constructor can be called. The compiler is even allowed to replace F_CONST with just the value 4 directly, which would also be a simple solution.

ActionScript 3 Singleton instantiation - advice

I have an AS3 Singleton:
package
{
public class Singleton
{
public function Singleton(enforcer:SingletonEnforcer):void
{
if(!enforcer){throw new Error("Only one instance of Singleton Class allowed.");}
}
private static var _instance:Singleton;
public static function getInstance():Singleton
{
if(!Singleton._instance)
{
Singleton._instance=new Singleton(new SingletonEnforcer());
}
return Singleton._instance;
}
}
}
class SingletonEnforcer{}
Consider prop and func() to be a property and method respectively of the Singleton class.
How should I access them?
1. Make them static and use this:
Singleton.getInstance();
Singleton.prop;
Singleton.func();
2. Not make them static and use this:
Singleton.getInstance().prop;
Singleton.getInstance().func();
Does it matter, or is it just visual prefference?
Thank you.
The reason to use a singleton instance is so that you can have class members used in a (relatively) static way.
I won't get into the arguments over whether or not to use a singleton here, there's a very long debate over whether it's a good pattern or not.
Typically, when singletons are used, you store access to them in a local variable and use them like any other class instance. The primary difference, is instead of using:
foo = new Foo();
You use:
foo = Foo.instance;
//Actionscript supports properties which makes this a self-initializing call
-or-
foo = Foo.getInstance();
Followed by
foo.bar();
foo.baz();
foo.fizz = 'buzz';
This doesn't mean that Foo can't have static members of the class, but the rules for adding static members on a Singleton are the same for adding static members to any other class. If the function belongs to the instance, it should be used on the instance, if it belongs to the class, it should be static.

AS3 - Retype/Cast an inherited variable permanently in a subclass?

Possibly bad practice but I'm not well versed in software design anyway (I'm sure this question would have been asked before but I can't seem to find the right terminology)...Anyhow, it's just another curiosity of mine I'd like to have answered.
So I have worked in a way where I type a base class variable to type Object or Sprite or something similar so that in my subclasses, I can instantiate my custom classes into them and store it. And when I access it, I just cast that variable to ensure I can access the methods.
Take this example, so that you know what I'm talking about:
public class BaseClass
{
protected var the_holder_var:Object;
public function BaseClass()
{
//Whatever abstract implementation here...
}
}
Now, my subclasses of that base class usually use an interface but for simplicity sake, I'll just write it without it.
public class AnExtendedClass extends BaseClass
{
public function AnExtendedClass()
{
//Instantiate my own class into the base class variable
this.the_holder_var = new ACustomClassOfMine();
//Then I can use the 'hackish' getter function below to
//access the var's functions.
this.holder_var.somefunction()
}
private function get holder_var():ACustomClassOfMine
{
return this.the_holder_var as ACustomClassOfMine;
}
}
This works and I'm sure it will make some ppl cringe (I sometimes cringe at it too).
So now, my question, is there a way to recast/retype that base var in my extended subclass?
kinda like this:
public class ExtendedClass extends BaseClass
{
//Not possible I know, but as a reference to see what I'm asking about
//Just want to change the type....
override protected var the_holder_var:ACustomClassOfMine;
public function ExtendedClass()
{
//Then I can forget about having that hackish getter method.
this.the_holder_var = new ACustomClassOfMine();
this.the_holder_var.somefunction();
}
}
I was thinking of typing most of my base class vars that I use as holders as type * and retyping them as I extend the class. (I could use it here too but yeah...)
Thoughts? Comments? Ideas?
I actually think your code (apart from the hypothetical addition at the end) is pretty alright. The practise of adding accessors to solve the type issue you're dealing with is a solid one. I would advise to rename the accessor to show it is a cast, maybe get holderVarAsCustom():ACustomClassOfMine (I'm also not a big fan of the underscores, that's another language's convention), but that's personal preference. What I'd do to solve your last problem is just create a matching setter function:
private function set holderVarAsCustom(value:ACustomClassOfMine):void {
this.the_holder_var = value;
}
This way you can access the correctly typed holder var for both read and write operations with complete type safety:
holderVarAsCustom = new ACustomClassOfMine();
holderVarAsCustom.someFunction();
I would definately advise against dropping the type safety by including arrays and what not, that just makes it unstable.
I must admit that i'm a little confused as to why you want to do this, but here goes. Could you not utilise the fact that Array's can hold different data types. So something like this:
public class BaseClass
{
protected var customStorage:Array;
public function BaseClass()
{
//Whatever abstract implementation here...
}
}
You could then access it with an associative method and a property:
public class AnExtendedClass extends BaseClass
{
private static const myName:String = "myName";
public function AnExtendedClass()
{
//Instantiate my own class into the base class variable
customStorage[myName] = new ACustomClassOfMine();
objectIWant.somefunction()
}
private function get objectIWant():ACustomClassOfMine
{
return ACustomClassOfMine(customStorage[myName]);
}
}
Is that any better?
I would not try to tinker this behaviour, since you can't change the declared type of a variable once declared, no matter how hard you try.
What I do in such cases, I either cast the variable if I use it sparingly or the object it references may change, or I add another variable with the type I want and let the other variable point to the new one. Like this:
public class A {
protected var object:Object;
public function A() {
//Whatever abstract implementation here...
}
}
and
public class B extends A {
protected var other:MyClass;
public function B() {
super();
this.other = new MyClass();
this.object = this.other;
}
}
Having it this way, class A uses the object via the this.object reference, and class B can use the this.other or both. But both references point to the same object. The only issues with this are:
having two references for in the same class to the same object is ugly (so are untyped variables and casts)
if the object one of them may point can change during runtime, you must be really carefull to synchronize these changes

Should a class ever have static and non-static members

I'm trying to figure out when it would be appropriate for a class to have both static and non-static functions. AKA:
$obj = new ClassA;
$obj->doOOPStuff();
$something = ClassA::doStaticStuff();
Note: This example is done in PHP, however the question is language agnostic .
It seems that if you have a class that is meant to be instantiated, any functions that can be called statically, most likely belong in another class.
Is there any viable cases where I would have a class that used static AND non-static members?
One example: when Creation has to happen in a specific way.
class Foo {
public:
static Foo* Create(...params...);
private:
Foo();
};
Consider String class in .NET. It contains a non-static Split method which breaks some instance into a string[] and a static Join method, which takes a string[] and transform it into a string again.
A static method is applicable when you don't need to keep any state. So Math.Sin() just depends on its parameters and, given same parameters, output will always be the same. A non-static method can have different behavior is called multiple times, as it can keep a internal state.
If the functionality provided by static methods is relevant to that class and its objects, why not. It is pretty common.
Static method are most often factory methods
public class MyClass {
public static MyClass createMyClass(int a, double b) {..}
public static MyClass createSubclassOfMyClass(int c, boolean cond) {..}
public int calculateThis();
public double calculateThat();
}
Another use is to access some property that is logically bound that that class, but not separately to instances. For example - a cache:
(Note - of course synchronization should be taken into account in this example)
public class MyClass {
public static final Cache cache = new Cache();
public static void putInCacheIfNeeded(Object obj) {..}
public static void replaceInCache(Object obj) {..}
public void doSomethingCacheDependend(Object obj) {
if (something) {
MyClass.putInCacheIfNeeded(obj);
} else {
MyClass.replaceInCache(obj);
}
}
}
(Java language for the examples)
Imagine your constructor has two overloads that both are strings:
public class XmlDocument
{
public static XmlDocument CreateFromFile(string filePath);
public static XmlDocument CreateFromXml(string xml);
}
The static function can provide meaningful name to the constructor.
$dialog = DialogFoo::createOpenDialog();
$dialog = DialogFoo::createDocumentOpenDialog();
$dialog = DialogFoo::createImageOpenDialog();
It could also be used to enforce Singleton pattern.
$dialog = DialogFoo::getInstance()
Static class members are most useful where everything must either be in an object or be in a global scope; they are less useful in a language such as Python that supports module-level scopes.
I use static methods to instantiate new objects when I dont want the to give access to the constructor. I ensure that any necessary preconditions are carried out on the class before creating and object. In this example I have a counter to return how many objects are created, if I have 10 objects I prevent any more from being instantiated.
class foo {
private:
static int count;
foo() {}
public:
static foo bar() {
count++;
if (count<=10){
return new foo;
} else {
return null;
}
Let's assume a class has instance methods, here are some good use case for having static methods too:
For static utility methods
Such methods apply to any instance, for example String.format(String, Object...) in Java.
Use them when you don't want to create a specific instance for the job.
For static factory methods
Factory methods are methods that simply instantiate objects like the getInstance() and valueOf() methods in the Java API. getInstance() is the conventional instantiation method in singletons while valueOf() are often type-conversion methods, like in String.valueOf(int).
Use them to improve performance via object-caching, in interface-based frameworks (like the Collections Framework in Java) where you may want to return a subtype, to implement singletons (cough).
In general, static functions produce functionality highly related to class itself. It may be some helper functions, factory methods etc. In this case all functionality contains in one place, it correspond to DRY principle, increases cohesion and reduces coupling.