Azzera filtri
Azzera filtri

If there are no inputs to a class, how to set defaults as properties of different classes under their respective classes?

1 visualizzazione (ultimi 30 giorni)
I am new to OOP and would like to know how to set default properties of a class without the class inheriting the subclass properties individually. For example, I have two classes, "dog" and "cat", where each of these classes have multiple properties each (you can think of these as breeds). Now, I have a class "animals", I want this class to be able to take in edited Dog and Cat properties, BUT if they aren't provided I want the properties to be the default properties from classes dog and cat. Right now the following code for the animals class is as follows:
classdef animals < handle
properties
DOG % An instance of the DOG class
CAT % An instance of the CAT class
end
methods
function obj = animals(Dog,Cat)
if nargin==0
% obj.DOG = dog; % If there is no input, default obj.DOG to have properties from dog class
% obj.CAT = cat; % If there is no input, default obj.CAT to have properties from cat class
elseif nargin==2
obj.DOG = Dog(); % Create an instance of Dog
obj.CAT = Cat(); % Create an instance of Cat
end
end
end
end
I know it's possible for the "animals" class to inherit the properties of the dog and cat, but I don't want the properties to be individually under "animals" I want them to be under animals.dog.shepard or, another example, animals.cat.tabby. How can I fix lines 9 and 10 so that the default properties from dog and cat are default under animals?

Risposte (1)

Eryn Jaramillo
Eryn Jaramillo il 19 Lug 2023
In case this helps anyone, I solved my problem by correcting the code as follows.
classdef animals < handle
properties
DOG = dog % An instance of the DOG class
CAT = cat % An instance of the CAT class
end
methods
function obj = animals(Dog,Cat)
if nargin==2
obj.DOG = Dog(); % Create an instance of Dog
obj.CAT = Cat(); % Create an instance of Cat
end
end
end
end
If this is bad coding practice, I welcome any advice, but this is what I have gotten to work for me for now. Thanks!

Categorie

Scopri di più su Specifying Target for Graphics Output in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by