java
一个.java中有多个class
里面有多个class时,只能有一个为public
//桥接模式代码,就是说里面只能有一个public,通常为文件名即main入口
package simplefactory;
interface Shape {
void draw();
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
class ShapeFactory {
//使用 getShape 方法获取形状类型的对象
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
//在这里
public class simplefactory {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//获取 Circle 的对象,并调用它的 draw 方法
Shape shape1 = shapeFactory.getShape("CIRCLE");
//调用 Circle 的 draw 方法
shape1.draw();
//获取 Rectangle 的对象,并调用它的 draw 方法
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//调用 Rectangle 的 draw 方法
shape2.draw();
//获取 Square 的对象,并调用它的 draw 方法
Shape shape3 = shapeFactory.getShape("SQUARE");
//调用 Square 的 draw 方法
shape3.draw();
}
}
public 权限的类最多有一个,作为main的入口。若这个文件中没有public的类,则文件名随便是一个类的名字即可
interface与abstract
interface是接口,里面的函数必须要全部实现
abstract里面函数不需要全部实现。
C++
抽象类与虚函数
C++抽象类的方法是在里面写虚函数。
virtual void phonate(){};//虚函数写法
virtual void twinkle()=0;//纯虚函数写法
·虚函数可以不重写,纯虚函数必须重写。
·可以通过该基类派生出各种对象,而该基类不能实例化。
C++与java互换
C++
1.C++里面class后面要加分号
2.C++里面没有abstract和implement
3.C++继承是这样的
class PoliceCarAdapter :public CarController
java
还没想好写啥
二者对比
C++写法
PoliceSound *sound=new PoliceSound();
sound->alarmSound();
JAVA写法
PoliceSound sound=new PoliceSound();
sound.alarmSound();