I don't know how to express 'property belongs to its owner' properly.
For example, I define classes 'student' and 'teacher'
classdef student < handle
properties
name
homework
end
methods
function obj = student(name)
obj.name = name;
obj.homework= struct;
obj.homework.content='';
obj.homework.mark=[];
end
end
end
classdef teacher < handle
properties
collection_homework
end
end
A=student('A')
A.homework.content='A solution to a math problem'
B=teacher
My question is, according to my design intention, homework is a property of a student, or ‘A is the owner of his homework’. A 'sends' his homework to B, a teacher , so the homework becomes a property of B, but B is not 'the owner' of A's homework. What can teachers do is just to mark the homework and return the homework to students.
But when I try to "send A's homework to B", and B marks A's homework
B.collection_homework=A.homework % put A's homework into B's collection_homework
B.collection_homework.mark=100
I check A, but his homework still is all about content, not mark
A.homework
ans =
content: 'A solution to a math problem'
That means homework in B's collection_homework doesn't belong to A.
Unless I put 'the whole student' into teacher's collection_homework
B.collection_homework=A % put A into B's collection_homework
B.collection_homework.homework.mark=100
This time I can get B to mark A's homework. Check it
A.homework.marks
ans =
100
But this is against with my design intention, because A seems to become B's subproperty. For example, B can change A's name by
B.collection_homework.name = 'C'
So what the code should be like to implement 'A send homework to B, and B mark it and send back to A'?
CodePudding user response:
The key point is to define 'homework' as another class
classdef homework < handle
properties
content
mark
end
end
And change definition of 'student'
classdef student < handle & matlab.mixin.Heterogeneous
properties
name
homework
end
methods
function obj = student(name)
obj.name = name;
obj.homework = homework();
end
end
end
change definition of 'teacher'
classdef teacher < handle
properties
collection_homework
end
methods
function obj = teacher()
obj.collection_homework=homework.empty(0,1);
end
end
end
Now test it!
A=student('A');
A.homework.content='A solution to a math problem';
B=teacher;
B.collection_homework=A.homework;
B.collection_homework.mark=85;
>>B.collection_homework
ans =
homework - Properties:
content: 'A solution to a math problem'
mark: 85
>> A.homework
ans =
homework - Properties:
content: 'A solution to a math problem'
mark: 85
It seems that student and teacher have the same homework. Teacher grades it, and student recieve it.