为什么编译器在将子类对象分配给父类引用时不会抛出错误?

huangapple go评论65阅读模式
英文:

Why is the compiler not throwing error when Assigning object of sub class to parent reference

问题

class Base {
	public void show() {
		System.out.println("Base class show() method called");
	}
}

class Derived extends Base {
	public void show() {
		System.out.println("Derived class show() method called");
	}
}

public class Main {
	public static void main(String[] args) {
		Base b = new Derived();
		b.show();
	}
}
class Derived extends Base {
	public void show() {
		System.out.println("Derived class show() method called");
	}
	public void poo() {
		System.out.println("take a poo");
	}
}

public class Main {
	public static void main(String[] args) {
		Base b = new Derived();
		b.show();
		// b.poo(); // This line would result in a compilation error.
	}
}

Java allows assigning a reference of a child class to a base class because of polymorphism, but it won't allow accessing methods specific to the child class unless you cast the reference to the child class type.

英文:
class Base {
	public void show() {
		System.out.println("Base class show() method called");
	}
}

class Derived extends Base {
	public void show() {
		System.out.println("Derived class show () method called");
	}
}

public class Main {
public static void main(String[] args) {
	Base b = new Derived();//why is java allowing me to create an object of child class
	b.show();              //how can the Base class hold and use the reference of child
	}                              
}

What if I create an new method in the child class ??
Will the parent class still be able to access the new method ??

class Derived extends Base {
	public void show() {
		System.out.println("Derived class show () method called");
	}
	public void poo() {
		System.out.println("take a poo");
	}
}

public class Main {
public static void main(String[] args) {
	Base b = new Derived();
	b.show();   
        b.poo(); 
	}                              
}

Why is java allowing me to assign a reference of child to base class and not throwing any warnings or errors.

答案1

得分: 1

这被称为多态性。任何派生类都可以被视为父类的实例(无需显式转换)。

您可以调用的方法和可以访问的字段取决于对象的静态类型。在Base b = new Derived();的情况下,b的静态类型是Base,因此只能调用Base上可见的方法。在Derived中定义的新方法无法使用。

英文:

This is called polymorphism. Any derived class can necessarily be considered an instance of a parent class (without explicit casting).

The methods you can call and fields you can access depend on the static type of the object. In the case of Base b = new Derived();, the static type of b is Base, so you can only call methods visible on Base. New methods defined in Derived cannot be used.

huangapple
  • 本文由 发表于 2023年5月18日 00:53:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定