Colobot Wiki
Advertisement

This keyword is used in a class definition when we want the class to inherit members from another class. The class which is extended we usually call a parent or base, the extending class we call a child.

Example:[]

public class Parent
{
	void foo()
	{
		message("foo");
	}
}


public class Child extends Parent
{
	void bar()
	{
		message("bar");
	}
}


extern void object::Test()
{
	Child child();
	child.foo(); // Will show "foo"
	child.bar(); // Will show "bar"
}

Inherited Members[]

Only public and protected members are inherited. Private members are directly inaccessible even for a child, although they can be accessed indirectly through inherited methods.

Constructors and destructors are not inherited, however, they can be overridden.

Method Overriding[]

Inherited methods can be overridden (redefined) in the child class definition.

Example:[]

public class Parent
{
	void foo()
	{
		message("foo");
	}
}


public class Child extends Parent
{
	void foo()
	{
		message("bar");
	}
}
extern void object::Test()
{
	Child child();
	child.foo(); // Will show "bar"
}

A parent's method can be called inside an overridden method by using the super keyword.

Polymorphism[]

Reference of type parent can point to an object of type child. However, such a pointer can't be used to access a child member. In order to access a child member, it must be assured that the parent reference really points to a child object. If that's the case, it can be safely copied to a pointer of type child, which has access to the child members.

Example:[]

public class Parent
{
	void foo()
	{
		message("foo");
	}
}
public class Child extends Parent
{
	void foo()
	{
		message("bar");
	}
	void bar()
	{
		message("foo bar");
	}
}
extern void object::Test()
{
	Parent people[2];
	people[0] = new Parent();
	people[1] = new Child();
	for (int i = 0; i < 2; ++i)
	{
		people[i].foo();
	}
	//people[1].bar(); // Error
	Child child = people[1];
	child.bar(); // OK
}

Multiple Inheritance[]

A child cannot have multiple parents, however, a parent can have many children.

See also[]

Class, public, private, protected, new, reference, this, super

Programming, types and categories.

Advertisement