int main(){
return 0;
}class Test{
public static void main(String arg[]){
//...
}
}Does having to write our main method in a class mean that Java is more Object-oriented than C++?
- No
class Animal {
public:
string name;
int legs;
}
class Cat : public Animal {
}
bool canEat(Animal &a) {
return a.legs < 6;
}
int main() {
Cat cat;
canEat(cat); // => True
}Cat is a derived class (or subclass or subtype) of Animal.
- Subclass: A class that has all the members of another class
- Subtype: A type that can be used as a substitite when another type is needed
Can I have a subclass that is not a subtype?
Yes, for example:
class Cat : private Animal {
//...
}Since Cat privately inherits from Animal this means that methods that expect Animal will not accept Cat objects.
Can I have a subtype that is not a subclass?
Yep. int is a subtype of double, but not a subclass of double.
subtypes of double in C++:
- char
- bool
- int
None of these are subclasses.
double timesTwo(double X){
return x*2;
}
int main(){
int foo = 5;
timesTwo(foo);
}Single interface to actions on values of different types
example: something.makeSounds() will work for different types of something and make or may not produce different outputs
There are two types of polymorphism:
- Parametric
- Ad Hoc
examples of parametric polymorphism: Reverse works with many different types
-- Parameteric Polymorphism
reverse :: [foo] -> [foo]template <T>
class vector {...}
vector<foo> vf;examples of ad hoc polymorphism: show only works with types that have implemented the Show interface
-- Ad Hoc Polymorphism
show :: Show a => a -> StringThis C++ code assumes that > exists for type T which is why it is ad hoc.
template <T>
T max(T a, T b){
if (a > b)
return a;
else
return b;
}What does the following code print out?
class A {
void f(){
cout << "a";
}
}
class B : public A{
public:
void f(){
cout << "b";
}
}
int main(){
A *a = new A;
A *b = new B;
a->f();
b->f();
}Answer:
aa
If A defined f as a virtual function then this code would print out a b.
Non-virtual methods use early binding.
Virtual methods use late binding.
There's also something called very late binding.
class A:
def __getattr_(self, name):
def answer(*args):
print("You called A.", name)
return answerUsing this code, I can call any unwritten function on object of type A and it will print "You called A.whatever"
Very late binding would be useful for a Proxy Object.
# Send method calls to big computer and get response
# (we are a little computer)
class Proxy:
def __getattr(self, name):
def answer(*args):
m = Message(name, args)
result = sendOverNetwork(bigcomputer, m)
return resultLet's look at our code from earlier:
class A {
void f(){
cout << "a";
}
}
class B : public A{
public:
void f(){
cout << "b";
}
}
int main(){
A *a = new A;
A *b = new B;
a->f();
b->f();
}For each class a Virtual Method Table is created.
The Virtual Method Table Pointer is the pointer that points to the VMT for a class.
#proglang-f19