引用类型使用总结
1. 类名作为方法参数和返回值
public class Person {
String name;
int age;
public Person ( ) {
}
public Person ( String name, int age) {
this . name = name;
this . age = age;
}
}
public class Test {
public static void main ( String[ ] args) {
Person p = new Person ( "张三" , 18 ) ;
method1 ( p) ;
System. out. println ( p. name+ "," + p. age) ;
}
public static void method1 ( Person p) {
p. age = 19 ;
}
}
public class Test2 {
public static void main ( String[ ] args) {
Person p1 = method2 ( ) ;
System. out. println ( p1. name+ "," + p1. age) ;
}
public static Person method2 ( ) {
Person p = new Person ( "李四" , 18 ) ;
return p;
}
}
2. 抽象类作为方法参数和返回值
抽象类作为形参:表示可以接收任何此抽象类的"子类对象"作为实参; 抽象类作为返回值:表示"此方法可以返回此抽象类的任何子类对象";
public abstract class Animal {
public abstract void eat ( ) ;
}
public class Dog extends Animal {
@Override
public void eat ( ) {
System. out. println ( "狗吃骨头..." ) ;
}
}
public class Test {
public static void main ( String[ ] args) {
Dog dog = new Dog ( ) ;
method ( dog) ;
method ( new Animal ( ) {
@Override
public void eat ( ) {
System. out. println ( "吃..." ) ;
}
} ) ;
}
public static void method ( Animal anl) {
anl. eat ( ) ;
}
public static Animal method2 ( ) {
return new Animal ( ) {
@Override
public void eat ( ) {
System. out. println ( "吃..." ) ;
}
} ;
}
}
3. 接口作为方法参数和返回值
接口作为方法的形参:【同抽象类】 接口作为方法的返回值:【同抽象类】
public interface IA {
void show ( ) ;
}
public class Test {
public static void main ( String[ ] args) {
method1 ( new IA ( ) {
@Override
public void show ( ) {
System. out. println ( "show..." ) ;
}
} ) ;
}
public static void method1 ( IA ia) {
}
public static IA method2 ( ) {
return new IA ( ) {
@Override
public void show ( ) {
}
} ;
}
}
4. 类名作为成员变量
public class Person {
String name;
IdCard idCard;
}
public class IdCard {
String idNum;
}
public class Test {
public static void main ( String[ ] args) {
Person p = new Person ( ) ;
IdCard id = new IdCard ( ) ;
id. idNum = "401234567890" ;
p. name = "张三" ;
p. idCard = id;
System. out. println ( p. idCard. idNum) ;
}
}
5. 抽象类作为成员变量
抽象类作为成员变量——为此成员变量赋值时,可以是任何它的子类对象
public abstract class Animal {
}
public class Dog extends Animal {
}
public class Person {
Animal anl;
}
public class Test {
public static void main ( String[ ] args) {
Person p = new Person ( ) ;
p. anl = new Dog ( ) ;
}
}
6. 接口作为成员变量
interface Animal {
}
class Dog implements Animal {
}
class Person {
Animal anl;
}
public class Test {
public static void main ( String[ ] args) {
Person p = new Person ( ) ;
p. anl = new Dog ( ) ;
}
}