![](/img/trans.png)
[英]How does the parent class's defined method get called in a sub-class object?
[英]How to call an Object's Method from another class without creating a sub-class and/or inheriting class?
我一直在初学阶段学习基本代码。 现在我终于开始涉足实际编写简单的程序,并且真的陷入困境。
我正在写一个简单的程序,它由两个类组成; 人,MainPage。
程序运行后,方法openApp()
在main方法中从(MainPage Class)调用。
public static void main(String[] args) { openApp(); }
接下来,当调用openApp()
,用户有三个菜单可供选择,通过输入相应的数字来选择
即1 =新闻源,2 =个人资料或3 =朋友。
公共类MainPage {
public static void openApp() {
System.out.println("Welcome to App!");
System.out.println();
System.out.println("To Select Option for:");
System.out.println("Newsfeed : 1");
System.out.println("Profile : 2");
System.out.println("Friends : 3");
System.out.println("Enter corresponding number: ");
int optionSelected = input.nextInt();
switch (optionSelected) {
case 1: System.out.println("NewsFeed");
break;
case 2: System.out.println("Profile");
break;
case 3: System.out.println("Friends");
break;
if (optionSelected == 3) {
people.friend();// Is it possible to write: friend() from "People" Class without extending to People Class
}
}
}
friend(People name)
,用于打印人对象的朋友。 我的尝试:
if (optionSelected == 3) {
people.friend();
}
我得到的错误:
线程“main”中的异常java.lang.Error:未解决的编译问题:无法解析人员
问题是我不想在MainPage中扩展People Class并继承它的所有方法,但我仍然想从People Class调用Object方法来打印people对象的朋友。
注意:以防任何人想要查看位于People类中的friend(People people)
方法:
public void friend(People people) {
System.out.println(people.friend);
优秀的问题格式。
您可以声明类型为People
的Object
,并使用它。
例
public class MainPage
{
People people = new People();
// .. Some code.
if(optionSelected == 3) {
people.friend();
}
}
说明
您的friend
方法是一种instance method
。 这意味着要访问它,您需要创建一个对象实例。 这是通过new
关键字完成的。 其次,除非People
是某种形式的实用类,否则你的friend
方法应该更像是:
public void friend()
{
System.out.println(this.friend);
}
为了良好的代码设计,请记住您的MainPage
类正在输出给用户,因此您应该return
值而不是打印它。 其次,您应该遵循良好的命名标准,在Java
我们在获取类成员时使用get
前缀。
public void getFriend()
{
return this.friend;
}
在MainPage
类中,您应该打印它。
if(optionSelected == 3)
{
System.out.println(people.getFriend());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.