我在子类中重写了2种父方法,但我没有得到
Object ooj = new String("abc");
的工作方式
据我所知,运行时对象是字符串类型,但是当我传递obj
使其起作用时,它将调用Object
类型的方法
PARENT CLASS
public class Parent {
public void function(Object obj) {
System.out.println("I'm parent Object Type");
}
public void function(String str) {
System.out.println("I'm parent String");
}
}
CHILD CLASS
public class Chile extends Parent{
public void function(Object oob) {
System.out.println("I'm child object");
}
public void function(String str) {
System.out.println("I'm child string");
}
public static void main(String[] args) {
Parent p = new Chile();
Object obj = new String("Gaurav");
p.function(obj);
String str = new String("and");
p.function(str);
}
}
我的问题是为什么它调用Object
方法,为什么不使用字符串
答案 0 :(得分:4)
我的问题是为什么它调用对象方法而不是字符串
因为编译器不再知道它是#include <iostream>
#include <ctype.h>
#include <cstring>
int main()
{
std::cout << "Enter your new password: ";
std:: string password{};
std::cin >> password;
bool veryweak;
bool weak;
bool strong;
bool verystrong;
if (password.length() < 8)
{
for (int i = 0; i < password.length(); i++)
{
if (isdigit(password[i]))
{
veryweak = true;
}
else if (isalpha(password[i]))
{
weak = true;
}
}
}
else if (password.length() >= 8)
{
for (int i = 0; i < password.length(); i++)
{
//if (password has digits and alphabets)
//strong = true;
//if (password has digits and alphabet and special characters)
//verystrong = true;
}
}
else
{
std::cout << "Password is invalid.";
}
//---------------------------------------------------------------------------------------------------------------------
if (veryweak)
{
std::cout << "Your password is very weak.";
}
else if (weak)
{
std::cout << "Your password is weak.";
}
else if(strong)
{
std::cout << "Your password is strong.";
}
else if (verystrong)
{
std::cout << "Your password is very strong.";
}
return 0;
}
。
编译器决定要调用的重载,这不是在运行时决定的。您正在向其传递对String
的引用,因此它将查找接受Object
的方法。如果所引用的对象可以是更特定的类型,就不必费心去尝试。