I already know that you create an Interface within VB6.
Classes that implement an interface must implement ALL routines.
Is there a way to create something like an abstract class that may implement some routines.
Derived class must implement the abstract routines and may override the routines already implemented by the abstract class.
Please notice that we're talking about VB6 and not VB.NET or whatsoever.
Thank you
One work-around I use is to have an instance of the base class as a private member:
Implements Shape
Dim base as Shape
Dim radius as Single
Public Function Shape_Area() as Single
Shape_Area = pi*pi*radius
End Sub
Public Function Shape_PenColour() as Long
Shape_PenColour = base.PenColour() ' let the base do its thing
End Function
You could work up a hierarchy like that (for Square):
Implements Shape
Dim base as Rectangle
Public Function Shape_Area() as Single
Shape_Area = base.Area() ' which is Rectangle.Shape_Area which then calls the Shape.Area
End Sub
It does means that each class has to really know about the one it derives from. That may or may not be an issue for you. I have used it and it works well.
It does mean you have to do more work and each class explicitly
Visual Basic 6 does not support implementation inheritance, only interface inheritance. You can read more about it Here. There's a nice article here about interfaces and inheritance in VB6 that may lead you to a solution to your problem within VB6 capabilities.
A work-around (not a solution):
An interface, for instance, specifies routine A and B, implementing the second one.
A derived class has a private member being an instance of the interface.
The implementation of the routine B simply invokes that method on its private member.
Of course, we're dealing with 2 different objects but in some cases this may be good enough.
Implementation inheritance is over-rated and almost always ends up with complicated designs.
What you want to do achieve (provide base impl, reduce repeating code in derived classes, etc) can be done with composition and events
Consider interface IBase
Public Function GetArea() As Double
End Function
interface IDerived
Property Get Base() As IBase
End Property
Common implementation StdBaseImpl of IBase
Implements IBase
Event CustomizeArea(Value As Double)
Public Function GetArea() As Double
GetArea = 42
RaiseEvent CustomizeArea(GetArea)
End Function
Private Function IBase_GetArea() As Double
IBase_GetArea = GetArea
End Function
Then for derived classes you use composition and choose which base events to implement
Implements IDerived
Private WithEvents m_oBase As StdBaseImpl
Private Property Get IDerived_Base() As IBase
Set IDerived_Base = m_oBase
End Property
Private Sub m_oBase_CustomizeArea(Value As Double)
Value = Value + 10
End Sub
You can design bases with BeforeXxx + Cancel and AfterXxx events. You can sink multiple bases and coordinate them.
Related
So we know that Java 8 method references can be used to replace anonymous class creation. I'm curious if there's a way to use them to define named classes that implement a functional interface, something -- vaguely -- along the lines of
public interface Bar {
String returnSomeString();
}
public class Foo implements Bar = someObjectInstance::toString;
I know you can't use equals in defining a class, but something like that...
In OOP, class fields are characterized with several mutually exclusive options:
public vs private
final vs changeable (?)
static vs instance
Are there any other important characteristics of classes in Java or other common OOP languages, such as C++ and C#?
In programming, object oriented programming is a tool that has unleashed the real power of computing. OOP allows a programmer to define their own types and subsets of variables that they are able to use. Types like integers, doubles, strings, are all defined as a certain set of bits in the computers memory, so OOP gives a programmer the power to create their own types of mailable objects that can have different characteristics.
Public vs Private
These words reference the access that one has to variables and methods within a certain class. Public variables and methods are accessible anywhere meaning they can be called outside of the class that it exists in. Private methods and variables on the other hand, can only be called in the class where they exist.
Eg:
public class Vehicle{
private int milesPerGallon;
public int getMPG{
return this.milesPerGallon;
}
}
Vehicle car1 = new Vehicle();
In this example, the variable milesPerGallon is private while the accessor method (getMPG()) that returns this value is public. So, in order to get the miles per gallon for the car1 object, the programming could not call car1.milesPerGallon. They would instead have to call car1.getMPG() because that method is public.
The use of private variables may seem counterintuitive, but private class members are a way to manage complexity. If all members were public, then bugs and problems in code could be linked to any one of these public members. It is difficult to trace back problems to public members becasue they can be called anywhere. If something were to happen to a pri
A private member, by contrast, can only be accessed from inside the same class, so if something goes wrong with that, there is usually only one source file to look at. If you have a million lines of code in your project, but your classes are kept small, this can reduce your bug tracking effort by a factor of 1000.
-tdammers
Final vs Changeable
These two concepts refer to the malleability of variables within a class. If a member is final, this means that it cannot be changed later in the program. But without the final keyword, then the variables are free to change at any time. Say for example, you were writing a cash register class.
public class Register{
private final double valueOfPenny = .01;
private final double valueOfNickel = .05;
ect...
private int numberOfPennies;
private int numberOfNickels;
ect...
}
In the Register class you will obviously need to know the value of a penny, nickel, dime, ect. But these values are going to stay constant through out the program. So we can set the value of each coin to be a final variable so that it does not accidentally get changed on accident. On the other hand, the number of each coin inside of the register may change through out the program, so we cannot make these variables final.
Static vs Instance
A instance variable means that every object has its own copy of each instance variable. An easy way to remember this is to think that every instantiation of a variable has a copy of the instance variable in a class. By default, all variables of a class are instance variables.
Static variables on the other hand, belong only once to the entire class. No matter how many instantiations of the class have been made, the static variable still only belongs to the class as a whole.
Eg:
public class Vehicle{
private double milesPerGallon;
public static int numberOfVehicles;
}
Vehicle car1 = new Vehicle();
Vehicle car2 = new Vehicle();
Both car1 and car2 have a variable called milesPerGallon. This makes sense because different instances of the Vehicle class will have different values of MPG. But, the variable numberOfVehicles is static because it only acts as a counter for how many vehicles there are. Every vehicle does not need to know this information because it is pointless for car1 and car2 to know that there are 2 vehicles. Only the class must know the value of this variable.
Constructors
You asked if there was any additional information about OOP that would be important and I feel as if constructors are at the top of the list. The constructor is a method that gets called whenever a programmer makes a copy of a class. In other words, whenever the programmer makes a call and instantiates a class, the constructor is the first and only method that gets called. In Java, the constructor is required and the name of the constructor is the same name as the class. If you do not provide Java with a constructor, then it will generate a blank constructor for you. But the power of the constructor is very useful and should often be utilized. Let's go back to the Vehicle example. Let's say you want to make a vehicle that has a certain manufacturer and the year it was made. You can save these two pieces of information as private instance variables as we mentioned above. But every time a Vehicle object is created, you want these two variables to be set right away. (i.e. you want to construct the object).
public class Vehicle{
private makeOfVehicle;
private yearOfVehicle;
public Vehicle(String make, int year){ //constructor
this.makeOfVehicle = make;
this.yearOfVehicle = year;
}
}
Vehicle car1 = new Vehicle("Toyota",2005);
Vehicle car2 = new Vehicle("BMW",2002);
By using the constructor, you can set attributes of objects as they are created!
Please let me know if you have any questions concerning these concepts/code or any other OOP concepts
I am trying to understand what design pattern I am stumbling towards... please bear with me the language I am using is Matlab and the OO is a bit weak in some areas, and I am relatively inexperienced in implementing design patterns.
I have a ComplexObject in which the constructor was becoming overly complicated. To begin with my constructor allowed 0, 1 or 2 arguments, that is an "empty" ComplexObject, a ComplexObject built from a ModelObject, or a ComplexObject built from ModelObject+ConfigObject. (The ModelObject and ConfigObject are basic file parsers).
I can't overload constructors in Matlab, so I essentially switch'ed on the class type of the input arguments to the constructor, after I while I changed some of this to static methods so that the constructor was just an empty class initializer, and static ComplexObject.createFromModel and ComplexObject.createFromModelAndConfig classes produced ComplexObjects.
I then decided that my ComplexObject code was being dominated by all this construction stuff and the business logic wasnt clear, so I wrote a ComplexObjectFactory class and basically moved the static methods into that class. Now since the static methods are in fact calling more private (static!?) methods to build the ComplexObject I have run into some confusion about calling conventions of these private static methods :(
Finally, I am now trying to add some code to write part of ComplexObject back to disk. Interestingly this is actually the same disk file that is used to build a ConfigObject... so I want something like ComplexObject.writeConfigFile... or should that be ComplexObjectFactory.writeConfigFile(myComplexObject). To further complicate things I want multiple types of "config" file formats down the track.
My current classes look something like:
classdef ComplexObjectFactory
methods (Static)
function product = createFromModel(modelObj)
product = ComplexObject()
ComplexObjectFactory.helper1(product)
end
function product = createFromModelAndConfig(modelObj, configObj)
product = ComplexObjectFactory.createFromModel(modelObj)
ComplexObjectFactory.helper2(product, configObj)
end
end
methods (Private, Static)
function helper1(product)
function helper2(product)
end
end
classdef ComplexObject
methods
function self = ComplexObject(varargin)
<init>
end
end
end
classdef ComplexObject
Not sure I completely understand your question, tell me if I'm off topic here.
Just like you wrote, design pattern that creates objects is called factory. Other functionality that you mentioned, like writing to disk should be the responsibility of the object itself.
In Programming in Scala: A Comprehensive Step-by-Step Guide, the author said:
One way in which Scala is more
object-oriented than Java is that
classes in Scala cannot have static
members. Instead, Scala has singleton
objects.
Why is a singleton object more object-oriented? What's the good of not using static members, but singleton objects?
Trying for the "big picture"; most of this has been covered in other answers, but there doesn't seem to be a single comprehensive reply that puts it all together and joins the dots. So here goes...
Static methods on a class are not methods on an object, this means that:
Static members can't be inherited from a parent class/trait
Static members can't be used to implement an interface
The static members of a class can't be passed as an argument to some function
(and because of the above points...)
Static members can't be overridden
Static members can't be polymorphic
The whole point of objects is that they can inherit from parent objects, implement interfaces, and be passed as arguments - static members have none of these properties, so they aren't truly object-oriented, they're little more than a namespace.
Singleton objects, on the other hand, are fully-fledged members of the object community.
Another very useful property of singletons is that they can easily be changed at some later point in time to not be singletons, this is a particularly painful refactoring if you start from static methods.
Imagine you designed a program for printing addresses and represented interactions with the printer via static methods on some class, then later you want to be able to add a second printer and allow the user to chose which one they'll use... It wouldn't be a fun experience!
Singleton objects behave like classes in that they can extend/implement other types.
Can't do that in Java with just static classes -- it's pretty sugar over the Java singleton pattern with a getInstance that allows (at least) nicer namespaces/stable identifiers and hides the distinction.
Hint: it's called object-oriented programming.
Seriously.
Maybe I am missing something fundamentally important, but I don't see what the fuss is all about: objects are more object-oriented than non-objects because they are objects. Does that really need an explanation?
Note: Although it sure sounds that way, I am really not trying to sound smug here. I have looked at all the other answers and I found them terribly confusing. To me, it's kind of obvious that objects and methods are more object-oriented than namespaces and procedures (which is what static "methods" really are) by the very definition of "object-oriented".
An alternative to having singleton objects would be to make classes themselves objects, as e.g. Ruby, Python, Smalltalk, Newspeak do.
For static members, there is no object. The class really just is a namespace.
In a singleton, there is always at least one object.
In all honesty, it's splitting hairs.
It's more object oriented in the sense that given a Scala class, every method call is a method call on that object. In Java, the static methods don't interact with the object state.
In fact, given an object a of a class A with the static method m(), it's considered bad practice to call a.m(). Instead it's recommended to call A.m() (I believe Eclipse will give you a warning). Java static methods can't be overridden, they can just be hidden by another method:
class A {
public static void m() {
System.out.println("m from A");
}
}
public class B extends A {
public static void m() {
System.out.println("m from B");
}
public static void main(String[] args) {
A a = new B();
a.m();
}
}
What will a.m() print?
In Scala, you would stick the static methods in companion objects A and B and the intent would be clearer as you would refer explicitly to the companion A or B.
Adding the same example in Scala:
class A
object A {
def m() = println("m from A")
}
class B extends A
object B {
def m() = println("m from B")
def main(args: Array[String]) {
val a = new B
A.m() // cannot call a.m()
}
}
There is some difference that may be important in some scenarios. In Java you
can't override static method so if you had class with static methods you would not be able to customize and override part of its behavior. If you used singleton object, you could just plug singleton created from subclass.
It's a marketing thing, really. Consider two examples:
class foo
static const int bar = 42;
end class
class superfoo
Integer bar = ConstInteger.new(42);
end class
Now, what are the observable differences here?
in a well-behaved language, the additional storage created is the same.
Foo.bar and Superfoo.bar have exactly the same signatures, access, and so on.
Superfoo.bar may be allocated differently but that's an implementation detail
It reminds me of the religious wars 20 years ago over whether C++ or Java were "really" Object Oriented, since after all both exposed primitive types that aren't "really" objects -- so, for example you can't inherit from int but can from Integer.
I would like to pass an interface to a method signature which takes Object as its parameter, so I wonder about this question
public Stream GetViewStream(string viewName, object model, ControllerContext context)
instead of object I shall like to pass an interface Imodel, without modifying the signature. Is there a base class for interfaces?
Also in the new mvc2 is there a way to avoid controllercontext altogether?
I'd only answer the first question - Why there's no common base interface for all interfaces ?
First of all, there's no common pre-defined base interface for all interfaces, unlike the System.Object case. Explaining this can get very interesting.
Let us assume, you could have a common interface for all interfaces in the system. That means, all interfaces will need to force their implementations to provide implementation-details for that common base interface. In general, interface are used to give specific special behaviors to their concrete implementation classes. Obviously you only want to define an interface when you only know what to do and don't know HOW to do that. So, if you let there be a common base interface for all interface and force the implementations to expect them to provide details of how to do it - why would you want to do it ? What common task each class should do that varies from one another ?
Lets look at the other side of the coin, why we have System.object as base class of any .Net type - It is simple it gives you some methods that have COMMON implementation for any .Net type and for those methods that it might vary from type-to-type they have made it virtual ex: .ToString()
There's possibly no assumption of any
system-wide interface method which is
virtual/abstract to all its
implementations.
One common practice of using Interface is say, defining a particular behavior to any type. Like I'd have an interface IFlyable which will give Fly() to all types that implement IFlyable. This way I can play with any Flyable object regardless of its inheritance hierarchy coming into picture. I can write a method like this..
public void FlyTheObject(IFlyable flyingObject)
{
flyginObject.Fly();
}
It does not demand anything from the object but the implementation of the Fly() method.
EDIT
Additionally, All interfaces will resolve to Object because interfaces cannot be instantiated. The object is always of a concrete class that can be instantiated. This class may or may not implement your interface but as we know, any .Net type is ultimately based to System.Object, so you will be able to take the instance into an object type regardless of the fact if it implements a particular interface or not.
No, there is no base class for interfaces. Nor there is base interface for interfaces.
As for your second question (and partly first one) - what are actually you trying to do?
There is no base class for interfaces, but you can pass any interface variable e.g:
private IEnumerable<int> myInterfaceVariable = new List<int>();
to your method because by definition anything that is stored in that variable must be an instance of a class that inherits from the interface - therefore it must be an object.
The following compiles fine:
public class InterfaceAsObject
{
private IEnumerable<int> myInterfaceVariable = new List<int>();
private void CallDoSomething()
{
DoSomething(myInterfaceVariable);
}
private void DoSomething(object input)
{
}
}
Re 1, there is no base interface, but if I understand you correctly, you can achieve what I think you want by just passing your object that implements IModel via the model parameter and cast (and check!) the parameter to IModel. I use 'as' and check for null.
If you don't need total flexibility, a better way of doing this is to define the interface that the model parameter must support. If the specific objects support derived interfaces (e.g. IDerivedModel : IModel) this will work too.
Look up a text-book on polymorphism.