it's simple, i just want a explanation about this:
internal class B { // Base class
}
internal class D : B { // Derived class
}
in other class I wrote:
B b3 = new Object(); //compilation time error!
why??? We suposse that all classes inherit from "object"
B is more specialized than Object, therefore you cannot assign an Object instance to a B reference. This is because not every Object is actually a B - only the opposite is true.
Let's assume that you have a field x in the class B. When you instantiate an Object, no memory is reserved for this field, and if you could assign it to a reference of type B, it would therefore try to read or write to unallocated memory, which is not allowed (or useful).
All classes are objects, but not all objects are {someclass}.
In a similar way, all buses are vehicles, but not all vehicles are buses.
Related
I have a superclass called A and a subclass called B that inherits from A. The superclass's constructor looks like this:
A(String name, char displayChar, int hitPoints, Behaviour behaviour)
{
this.name = name;
this.displayChar = displayChar;
this.hitPoints = hitPoints
addBehaviour(behaviour);
}
A has attributes of name, displayChar, hitPoints, behaviour and has a method that calls addBehaviour which adds the behaviour to the object.
The subclass, B's constructor looks like this:
B(String name) {super(name, char 'b', 10, new WalkBehaviour()); }
Now my question is, does subclass B have an attribute of WalkBehaviour?
How would the UML diagram look like for this scenario? I know B inherits from A and A has Behaviour but does B has WalkBehaviour in this case? Since B doesn't have an instance variable of type WalkBehaviour in its class but only passes WalkBehaviour through its superclass's constructor.
does subclass B have an attribute of WalkBehaviour?
No. There is none declared. The superclass will do something with that new object but obviously it's hidden in the mist of its implementation.
Inheritance is nothing that involves multiple object creation. Your B instance is just a single one which does have attributes and operations like its super class.
Thus, in a SD, you will see only one life line for B:
As you can see the B instance will just issue a self-call to the super class's constructor.
Note: as #AxelScheithauer pointed out in the comment the super class will invoke addBehavior which can (but must not) be shown in the SD:
I find in Kotlin: Object documentation an example:
open class A(x: Int) {
public open val y: Int = x
}
interface B {...}
val ab: A = object : A(1), B {
override val y = 15
}
So I implemented that example with more meaningful names and I have no clue what is the reason of the interface among the comma separated list of supertypes to the object?
interface Toy {
fun play () {
println("Play, play....")
}
}
open class Ball(public open val color: String = "red") {}
val ball: Ball = object : Ball(), Toy {
override val color : String = "blue"
override fun play() {
println("Bounce, bounce...")
}
}
fun main(args: Array<String>) {
println(ball.color)
// no ball.play() here then why the interface in the example ???
}
You're correct, the interface B (or in your example, Toy) will not be directly accessible through this reference if A (or Ball) doesn't implement it.
Inheriting from that interface is probably just added here so that this example intended to show how constructor parameters are passed to a superclass can also show off inheriting from multiple types very quickly. Or at least that's what I gather from the text accompanying it:
If a supertype has a constructor, appropriate constructor parameters must be passed to it. Many supertypes may be specified as a comma-separated list after the colon.
To get to the issue of not being able to use the created object as a B (or Toy) here: this doesn't make the language feature useless, since the created object can still be used through its multiple interfaces through casting. For example, in your example, you can do this:
(ball as Toy).play()
Or in the original example, you could make the type Any, and then cast to the different interfaces as needed.
You have created an instance of an anonymous class that inherits from class Ball and at the same time implements interface Toy.
But, both of these types are exclusive, ie. Ball is not a Toy (in your example), so you cannot call play() on a reference to Ball.
I have a dictionary with Structs in it. I am trying to assign the values of the struct when I loop through the dictionary. Swift is telling me cannot assign to 'isRunning' in 'blockStatus'. I haven't been able to find anything in the docs on this particular immutability of dictionaries or structs. Straight from the playground:
import Cocoa
struct BlockStatus{
var isRunning = false
var timeGapForNextRun = UInt32(0)
var currentInterval = UInt32(0)
}
var statuses = ["block1":BlockStatus(),"block2":BlockStatus()]
for (block, blockStatus) in statuses{
blockStatus.isRunning = true
}
cannot assign to 'isRunning' in 'blockStatus'
blockStatus.isRunning = true
This does work if I change the struct to a class.
I am guessing it has something to do with the fact that structs are copied and classes are always referenced?
EDIT: So even if it is copying it.. Why can't I change it? It would net me the wrong result but you can change members of constants just not the constant themselves. For example you can do this:
class A {
var b = 5
}
let a = A()
a.b = 6
Your guess is true.
By accessing blockStatus, you are creating a copy of it, in this case, it's a constant copy (iterators are always constant).
This is similar to the following:
var numbers = [1, 2, 3]
for i in numbers {
i = 10 //cannot assign here
}
References:
Control Flow
In the example above, index is a constant whose value is automatically set at the start of each iteration of the loop.
Classes and Structures
A value type is a type that is copied when it is assigned to a variable or constant, or when it is passed to a function. [...] All structures and enumerations are value types in Swift
Methods
Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.
However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.
You can opt in to this behavior by placing the mutating keyword before the func keyword for that method:
You could loop through the array with an index
for index in 0..<statuses.count {
// Use your array - statuses[index]
}
that should work without getting "cannot assign"
If 'Y' in this case is a protocol, subclass your protocol to class. I had a protocol:
protocol PlayerMediatorElementProtocol {
var playerMediator:PlayerMediator { get }
}
and tried to set playerMediator from within my player mediator:
element.playerMediator = self
Which turned into the error cannot asign 'playerMediator' in 'element'
Changing my protocol to inherit from class fixed this issue:
protocol PlayerMediatorElementProtocol : class {
var playerMediator:PlayerMediator { get }
}
Why should it inherit from class?
The reason it should inherit from class is because the compiler doesn't know what kind your protocol is inherited by. Structs could also inherit this protocol and you can't assign to a property of a constant struct.
I think I understand Value Objects ( they have no conceptual identity, set of its attributes is its definition etc) and how they differ from Entities, but I'm still puzzled whether a value of a primitive type ( int, string ...) being assigned directly to property of an Entity is also considered a VO.
For example, in the following code an object ( of type Name ) assigned to Person.Name is a VO, but are values assigned to Person.FirstName, Person.LastName and Person.Age also considered VO?
public class Person
{
public string FirstName = ...
public string LastName = ...
public int Age = ...
public Name Name = ...
...
}
public class Name
{
public string FirstName = ...
public string LastName = ...
public int Age = ...
}
thank you
It doesn't matter if a value is a primitive type (such as string or int) or a complex type composed of primitive types (such as Name). What matters is that you think of it as a mere "value" without any identity -- then it is a value object.
The decision to keep it a primitive or wrap it in a class is an implementation detail. Specific types are easier to extend in the future / add functionality than primitive types.
Check this related question... Value objects are more an implementation thing that a "conceptual" one... If you think about it, singleton and flyweight pattern are about turning an object with an identity to an value object for optimization purposes... It's also related to choosing to implement something as mutable or immutable. You can always say that Person is immutable, but after a while, you are a "new" person with different attributes. It's an implementation decision, not a domain or conceptual one. (Immutable things tend to be value objects, and the mutable ones identity objects).
I am trying to understand type members in Scala. I wrote a simple example that tries to explain my question.
First, I created two classes for types:
class BaseclassForTypes
class OwnType extends BaseclassForTypes
Then, I defined an abstract type member in trait and then defined the type member in a concerete class:
trait ScalaTypesTest {
type T <: BaseclassForTypes
def returnType: T
}
class ScalaTypesTestImpl extends ScalaTypesTest {
type T = OwnType
override def returnType: T = {
new T
}
}
Then, I want to access the type member (yes, the type is not needed here, but this explains my question). Both examples work.
Solution 1. Declaring the type, but the problem here is that it does not use the type member and the type information is duplicated (caller and callee).
val typeTest = new ScalaTypesTestImpl
val typeObject:OwnType = typeTest.returnType // declare the type second time here
true must beTrue
Solution 2. Initializing the class and using the type through the object. I don't like this, since the class needs to be initialized
val typeTest = new ScalaTypesTestImpl
val typeObject:typeTest.T = typeTest.returnType // through an instance
true must beTrue
So, is there a better way of doing this or are type members meant to be used only with the internal implementation of a class?
You can use ScalaTypesTestImpl#T instead of typeTest.T, or
val typeTest:ScalaTypesTest = new ScalaTypesTestImpl
val typeObject:ScalaTypesTest#T = typeTest.returnType
If you don't want to instance ScalaTypesTestImpl, then, perhaps, you'd be better off putting T on an object instead of class. For each instance x of ScalaTypesTestImpl, x.T is a different type. Or, in other words, if you have two instances x and y, then x.T is not the same type as y.T.