「Java」戻り値の型がObjectのメソッドを作る方法
書式
private static クラス名 関数名() {
処理コード
return オブジェクト変数名}
使用例
1.mainクラス
package com.arkgame.demo;
public class ObjectDemo {
public static void main(String[] args) {
// 戻り値の型がオブジェクト
Person ps = getPerson();
System.out.println("年齢: " + ps.getAge());
}
// 関数の定義
private static Person getPerson() {
Person info = new Person();
info.setAge(24);
info.setUsername("user002");
return info;
}
}
package com.arkgame.demo;
public class ObjectDemo {
public static void main(String[] args) {
// 戻り値の型がオブジェクト
Person ps = getPerson();
System.out.println("年齢: " + ps.getAge());
}
// 関数の定義
private static Person getPerson() {
Person info = new Person();
info.setAge(24);
info.setUsername("user002");
return info;
}
}
package com.arkgame.demo; public class ObjectDemo { public static void main(String[] args) { // 戻り値の型がオブジェクト Person ps = getPerson(); System.out.println("年齢: " + ps.getAge()); } // 関数の定義 private static Person getPerson() { Person info = new Person(); info.setAge(24); info.setUsername("user002"); return info; } }
2.Personクラス
public class Person {
private String username;
private int age;
public Person() {
}
//get set省略
}
public class Person {
private String username;
private int age;
public Person() {
}
//get set省略
}
public class Person { private String username; private int age; public Person() { } //get set省略 }
結果
年齢: 24