interface Fruit{
public void eat() ;
}
class Apple implements Fruit{
public void eat(){
System.out.println("吃苹果。") ;
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("吃橘子。") ;
}
}
class Factory{
public static Fruit getInstance(String name){
Fruit f = null ;
if("apple".equals(name)){
f = new Apple() ;
}
if("orange".equals(name)){
f = new Orange() ;
}
return f ;
}
}
public class OODemo40{
public static void main(String args[]){
Fruit f = Factory.getInstance(args[0]) ;
f.eat() ;
}
}
Fruit f = Factory.getInstance(args[0]) ;这段代码里面的Factory.getInstance没有new 为什么直接可以用。什么情况下可以这么写
public void eat() ;
}
class Apple implements Fruit{
public void eat(){
System.out.println("吃苹果。") ;
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("吃橘子。") ;
}
}
class Factory{
public static Fruit getInstance(String name){
Fruit f = null ;
if("apple".equals(name)){
f = new Apple() ;
}
if("orange".equals(name)){
f = new Orange() ;
}
return f ;
}
}
public class OODemo40{
public static void main(String args[]){
Fruit f = Factory.getInstance(args[0]) ;
f.eat() ;
}
}
Fruit f = Factory.getInstance(args[0]) ;这段代码里面的Factory.getInstance没有new 为什么直接可以用。什么情况下可以这么写
f = new Apple() ;
}
if("orange".equals(name)){
f = new Orange() ;
}
这个不是new吗?以后把new说“实例化”,这样专业点:)
其中rgs[0]是你在运行的时候输入的第一个参数 如果是apple 则会调用getInstance(String name)
通过if("apple".equals(name)){
f = new Apple() ;
}
来创建一个apple对象
其中rgs[0]是你在运行的时候输入的第一个参数 如果是apple 则会调用getInstance(String name)
通过if("apple".equals(name)){
f = new Apple() ;
}
来创建一个apple对象
这个方法是静态的,调用的时候可以用类名直接调用,楼上几位说的很详细