ballerina 学习七 object 创建&& 初始化

在 ballerina 总中object 是一个包含public private 类型字段同时包含函数,需要开发人员进行自定义类型以及行为
说白了,就是类似面向对象的class

基本使用

  • 代码
import ballerina/http;
import ballerina/io;
type App object {
public {
int age,
string name,
}
private {
string email = "default@abc.com",
}
};
function main (string… args) {
App app =new ;
App app2 =new();
App app3=new App();
io:println(app);
io:println(app2);
io:println(app3);
}
  • 输出结果
{age:0, name:""}
{age:0, name:""}
{age:0, name:""}

object 初始化

  • 代码
import ballerina/http;
import ballerina/io;
type App object {
public {
int age,
string name,
}
private {
string email = "default@abc.com",
int[] marks,
}
new(age, name = "John", string firstname,
string lastname = "Doe", int… scores) {
marks = scores;
}
};
function main (string… args) {
App app1 =new (5,"demoapp",4,5);
io:println(app1);
App app2 = new(5, "Adam", name = "Adam", lastname = "Page", 3);
io:println(app1);
}
  • 输出结果
{age:5, name:"John"}
{age:5, name:"John"}

成员方法

import ballerina/http;
import ballerina/io;
type App object {
public {
int age,
string name,
}
private {
string email = "default@abc.com",
int[] marks,
}
new(age, name = "John", string firstname,
string lastname = "Doe", int… scores) {
marks = scores;
}
function getFullName() returns string {
return age + " " + name;
}

// 抽象方法
function checkAndModifyAge(int condition, int age);
};
// 实现抽象方法
function App::checkAndModifyAge(int condition, int age){
io:println("demo");
}

function main (string… args) {
App app1 =new (5,"demoapp",4,5);
io:println(app1);
App app2 = new(5, "Adam", name = "Adam", lastname = "Page", 3);
io:println(app1);
app1.checkAndModifyAge(1,3);
}
  • 输出结果
{age:5, name:"John"}
{age:5, name:"John"}
demo

对象赋值

如果两个对象的结构相同,那么就可以进行赋值操作

import ballerina/http;
import ballerina/io;
public type Person object {
public {
int age,
string name,
}

public function getName() returns string {
return name;
}
};
public type Employee object {
public {
int age,
string name,
string address,
}

public new(age, name, address) {
}
public function getName() returns string {
return name + " Doe";
}
public function getAge() returns int {
return age;
}
};
function main (string… args) {
Person p1 = new Employee(50, "John", "street1");
io:println(p1);
io:println(p1.getName());
}
  • 输出结果
{age:50, name:"John", address:"street1"}
John Doe

参考资料

https://ballerina.io/learn/by-example/object-initializer.html
https://ballerina.io/learn/by-example/object-assignability.html
https://ballerina.io/learn/by-example/object-member-functions.html

posted on 2018-05-18 13:23  荣锋亮  阅读(190)  评论(0编辑  收藏  举报

导航