Java |
class A
{
public void F() {
System.out.println("A.F");
}
public void G() {
System.out.println("A.G");
}
}
class B extends A
{
public void F() {
System.out.println("B.F");
}
public void G() {
System.out.println("B.G");
}
}
class Test
{
public static void main(String[] args) {
B b = new B();
A a = b;
a.F();
b.F();
a.G();
b.G();
}
}
the output:
B.F
B.F
B.G
B.G
class A
{
public void F() {
System.out.println("A.F");
}
}
class B extends A
{
public void F() {
System.out.println("B.F");
}
}
class C extends B
{
public void F() {
System.out.println("C.F");
}
}
class D extends C
{
public void F() {
System.out.println("D.F");
}
}
class Test
{
public static void main(String[] args) {
D d = new D();
A a = new B();
B b = new B();
C c = d;
a.F();
b.F();
c.F();
d.F();
}
}
the output:
B.F
B.F
D.F
D.F
override modifier
You cannot override to be more private
class A
{
public void F() {}
}
class B extends A
{
public void F() {}//cannot be private
}
class C extends B
{
public void F() {}
}
You can hide B.F by controlling runtime type
|
|
C# |
using System;
class A
{
public void F() {
Console.WriteLine("A.F");
}
public virtual void G() {
Console.WriteLine("A.G");
}
}
class B: A
{
new public void F() {
Console.WriteLine("B.F");
}
public override void G() {
Console.WriteLine("B.G");
}
}
class Test
{
static void Main() {
B b = new B();
A a = b;
a.F();
b.F();
a.G();
b.G();
}
}
the output:
A.F
B.F
B.G
B.G
using System;
class A
{
public virtual void F() {
Console.WriteLine("A.F");
}
}
class B: A
{
public override void F() {
Console.WriteLine("B.F");
}
}
class C: B
{
new public virtual void F() {
Console.WriteLine("C.F");
}
}
class D: C
{
public override void F() {
Console.WriteLine("D.F");
}
}
class Test
{
static void Main() {
D d = new D();
A a = d;
B b = d;
C c = d;
a.F();
b.F();
c.F();
d.F();
}
}
the output:
B.F
B.F
D.F
D.F
override modifier
class A
{
public virtual void F() {}
}
class B: A
{
new private void F() {} // Hides A.F within B
}
class C: B
{
public override void F() {} // Ok, overrides A.F
}
|
|