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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2014-05-18 使用ZeroClipboard解决跨浏览器复制到剪贴板的问题
2014-05-18 Font Awesome