I think I probably have some blind spot. The following code in test target actually works that I thought it should not: (MyHelper is private already, but the caller still can use myHelperFunc())
// both MyClass and MyHelper are in the same file
class MyClass: XCTestCase {
func testDoWork() {
MyHelper.myHelperFunc()
}
}
private class MyHelper {
static func myHelperFunc() -> String {
return "something"
}
}
If I move the code to main target (delete the XCTestCase), compiler immediately flag MyHelper is not accessible that seems the right behavior? Is there something specific for test target that I missed?
private at file scope is equivalent to fileprivate.
#testable import makes internal code accessible to a test target.
Access Levels in The Swift Programming Language explains how private works:
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file.
"The enclosing declaration" of MyHelper is "the file." This is perhaps a bit more clearly stated in the Declaration Modifiers section of the Swift Language Reference:
private
Apply this modifier to a declaration to indicate the declaration can be accessed only by code within the declaration’s immediate enclosing scope.
Again, the "enclosing scope" of MyHelper is the file. If MyHelper were enclosed in some other class, then it would be limited to that scope rather than the whole file:
// Things change if MyHelper has a different enclosing scope than MyClass.
class MyClass {
func testDoWork() {
MyHelper.myHelperFunc() // Cannot find 'MyHelper' in scope
}
}
class C {
// MyClass can't access C.MyHelper now.
private class MyHelper {
static func myHelperFunc() -> String {
return "something"
}
}
}
In your example, myHelperFunc() has no annotation, so it initially receives the default level of internal. This is noted in Access Levels again:
Default Access Levels
All entities in your code (with a few specific exceptions, as described later in this chapter) have a default access level of internal if you don’t specify an explicit access level yourself.
However, as noted in "Guiding Principle of Access Levels:"
No entity can be defined in terms of another entity that has a lower (more restrictive) access level.
It is not allowed for MyHelper.myHelperFunc() to have a broader access level than its encoding type (MyHelper), so it's limited to file scope (which is effectively the same as fileprivate).
I have a subclass whose inheritance chain breaks down to look like this:
InputAccessoryEnabledTextField : UITextField : UIControl : UIView : UIResponder
InputAccessoryEnabledTextField provides an override:
private var myInputAccessoryController: UIInputViewController?
override var inputAccessoryViewController: UIInputViewController? {
get { myInputAccessoryController }
set { myInputAccessoryController = newValue }
}
The code above, working as the solution I was seeking, is from the accepted answer (#Sweeper) to a question I just asked on S.O. It is overriding an instance property of UIResponder.
However, it doesn't make sense to me. How can/does it work?
How is it possible that UITextField, superclass to my subclass, honors an override provided my subclass (InputAccessoryEnabledTextField)?
Doesn't that violate the inheritance hierarchy? Shouldn't only subclasses of InputAccessoryEnabledTextField be able to see its override, not superclasses?
Or do overrides apply to the whole object, such that every inherited superclass sees the state of some arbitrary outermost subclass? Or, is it that the iOS text subsystem is doing some really convoluted stuff?
Maybe this is too abstract a question for S.O. and I don't mind closing or deleting it, Just posting this to avoid a 'dialog' in the comments that the bot complains about.
Note: I don't find much clarity about it in Inheritence chapter of Swift 5 documentation *
In short
This is indeed the overriding of properties. Swift deals with properties by generating code that is equivalent to accessing properties via a via getters and setters. This allows to override a property by overriding the getter and the setter.
More explanations
Your snippet is overriding of a property
In your code, InputAccessoryEnabledTextField indirectly inherits from UIResponder, which has an existing property inputAccessoryViewController.
Your code snippet defines a new private property myInputAccessoryController, and uses it in the overriding of the inherited property inputAccessoryViewController, and more precisely, the overriding of its getter and setter.
Purpose in the case of your snippet
In fact, the purpose of this overriding is even explained in the documentation of inputAccessoryViewController:
The value of this read-only property is nil.
But what's the use of a property that is real only and returns only nil?
If you want to attach custom controls to a system-supplied input view controller (such as the system keyboard) or to a custom input view (...), redeclare this property as read-write in a UIResponder subclass.
How can property overriding even work?
While property overriding may seem weird at the first sight, we realize that this is just the normal overriding mechanism once we have understood that:
The stored or computed nature of an inherited property isn’t known by a subclass—it only knows that the inherited property has a certain name and type. You must always state both the name and the type of the property you are overriding, to enable the compiler to check that your override matches a superclass property with the same name and type.
Here we see the power of Swift's properties. You can make any property public, and still benefit from encapsulation and specialization, overriding it like functions. The explanation is that a property has two faces:
the class-internal implementation details: is the property stored or computed ?
the implicit class interface for the external world, including for subclasses: the outside world use the getter and the setter. These can be overridden.
the same principle works for property observers such as didSet: you can override them even if the base class didn't define any special behavior for them.
Here a small unrelated but extreme toy example to illustrate this feature (I would not recommend its design ;-) ):
class Lense {
init (opticalZoom: Int) {
magnifyingFactor = opticalZoom
}
// stored property
// And has implicitly a getter and a setter
var magnifyingFactor : Int = 2
}
class ElectronicLense : Lense {
// overriden property
// it overrides getter and setter, and uses the propery of the super-class to store the value
override var magnifyingFactor: Int {
get { super.magnifyingFactor * 5 }
set { super.magnifyingFactor = newValue / 5 }
}
// pass through property
var opticalFactor : Int {
get {super.magnifyingFactor}
}
}
var le = ElectronicLense(opticalZoom: 3)
print ("Zoom: \(le.magnifyingFactor) with an optical factor \(le.opticalFactor)")
The following example code demonstrates that a Swift superclass experiences its own properties through outermost subclass overrides!
(The example below proves #RobNapier correct, which I initially confirmed by successfully overriding UIResponder.inputAccessoryViewController and observing my viewController activated when the keyboard pops up for my subclassed UITextView : UIResponder)
The Good:
Swift overrides as explained by #RobNaipier in comments, make sense, at least from certain points of view. And can obviously be exploited for its interesting flexibility
The Bad:
However, it isn't what I assumed, and I was somewhat stunned that inheritance works that way, because intuitively I realized that letting subclasses tamper with superclasses` view of themselves is potentially risky, especially if one doesn't know superclass implementation details (as is the case with UIKits proprietary implementation code Apple doesn't release the source to the public).
The Ugly:
So while Swift inheritance lets the inheritors achieve tweak things for interesting or useful effect, and could be very handy in some cases, in practical use, for example with UIKit, it does leads to anticipated problems and confusion.
The coup de grâce, which I'm grateful that Rob pointed out, is that, due to the anticipated downsides, class inheritance with UIKit is increasingly discouraged by Apple and struct+protocol has been adopted by SwiftUI.
class TheSuperclass {
var x = 5
init() {
print("How superclass sees it before subclass initialized: x = \(x)")
}
func howSuperclassSeesItselfAfterSubclassInit() {
print("How superclass sees it after subclass initialized: x = \(x)")
}
}
class TheSubclass : TheSuperclass {
override var x : Int {
get { super.x + 10 }
set { super.x = newValue }
}
override init() {
super.init()
print("How subclass sees it after superclass" +
"initialized: x = \(x), super.x = \(super.x)")
}
}
TheSubclass().howSuperclassSeesItselfAfterSubclassInit()
The above code when run in Playground displays the following:
How superclass sees it before subclass initialized: x = 5
How subclass sees it after superclass initialized: x = 15, super.x = 5
How superclass sees it after subclass initialized: x = 15
I've read this answer but I'm still confused. When looking at this example in the docs...
open class Base { }
class Derived : Base() { }
open class BaseCaller {
open fun Base.printFunctionInfo() {
println("Base extension function in BaseCaller")
}
open fun Derived.printFunctionInfo() {
println("Derived extension function in BaseCaller")
}
fun call(b: Base) {
b.printFunctionInfo() // call the extension function
}
}
class DerivedCaller: BaseCaller() {
override fun Base.printFunctionInfo() {
println("Base extension function in DerivedCaller")
}
override fun Derived.printFunctionInfo() {
println("Derived extension function in DerivedCaller")
}
}
fun main() {
BaseCaller().call(Base()) // "Base extension function in BaseCaller"
DerivedCaller().call(Base()) // "Base extension function in DerivedCaller" - dispatch receiver is resolved virtually
DerivedCaller().call(Derived()) // "Base extension function in DerivedCaller" - extension receiver is resolved statically
}
And regarding this quote
An instance of a class in which the extension is declared is called a dispatch receiver, and an instance of the receiver type of the extension method is called an extension receiver.
I assume that only instances of Base() and Derived() can be extension receivers, because we only defined extensions for those two classes. And I assume that only instances of BaseCaller() and DerivedCaller() can be dispatch receivers, because we only declare extensions inside those classes.
My confusion stems from the two comments at the bottom of the example where it says "dispatch receiver is resolved virtually" and "extension receiver is resolved statically". Are they referring to DerivedCaller() in both cases? Is DerivedCaller() a dispatch receiver in one line and an extension receiver in the next? How can it be an extension receiver if we never declare any extensions for it? Or are they referring to Base() as the dispatch receiver and Derived() as the extension receiver? How can Base() be a dispatch receiver, if it never declares any extensions?
I know that call() always resolves statically to use an instance of Base, and I know the version of Base.printFunctionInfo() will depend on what object I call the call() method on (either BaseCaller() or DerivedCaller()), but I'm confused about what those comments are saying. Thanks in advance!
I was originally confused by these two comments from the docs
"dispatch receiver is resolved virtually"
"extension receiver is resolved statically"
In the first comment, the "dispatch receiver" refers to the DerivedCaller() instance. It's virtual because they could've called the call() method on a BaseCaller() instance or a DerivedCaller() instance (but they ended up calling it on a DerivedCaller() instance). This first comment is concerned with which extension method to call, the one in BaseCaller or the one in DerivedCaller
In the second comment the "extension receiver" refers to the Derived() instance that gets passed into call(). This second comment is concerned with which member function get's called from inside the DerivedCaller class. The Base.printFunctionInfo() or the Derived.printFunctionInfo(). In this case the extension receiver is resolved statically, so instead of using Derived() it uses Base() instead because that's how my extension function is setup (and extension functions are always resolved statically).
This is much easier to understand if we realize that Base.printFunctionInfo() and Derived.printFunctionInfo() are much different functions, only named the same. If we rename them, this example becomes obviously clear:
open class BaseCaller {
open fun Base.printFunctionInfoForBase() {
println("Base extension function in BaseCaller")
}
open fun Derived.printFunctionInfoForDerived() {
println("Derived extension function in BaseCaller")
}
fun call(b: Base) {
b.printFunctionInfoForBase() // call the extension function
}
}
class DerivedCaller: BaseCaller() {
override fun Base.printFunctionInfoForBase() {
println("Base extension function in DerivedCaller")
}
override fun Derived.printFunctionInfoForDerived() {
println("Derived extension function in DerivedCaller")
}
}
In call() we only have a Base object, so we can only invoke printFunctionInfoForBase(), but we can't invoke printFunctionInfoForDerived() there. Then, we clearly see that printFunctionInfoForDerived() is really never invoked anywhere in this code.
In other words, Base.printFunctionInfo() and Derived.printFunctionInfo() are two overloads of the function. DerivedCaller provides overrides of BaseCaller functions.
I'm trying to represent a human wearing glasses near a window when a nearby explosion occurs. main is a sketch of what should be done during the explosion. Something should gather up a list of objects in proximity of the explosion and do specific things (such as shattering or melting) for each of them. The glass and window shatter as expected, but for some reason the human also shatters. Why?
package main
import "fmt"
type Human struct { Glasses }
type Glasses struct {}
type Shatterable interface { shatter() }
func (g Glasses) shatter() {}
type Window struct {}
func (w Window) shatter() {}
func main() {
h := Human{Glasses{}}
objectsInProximity := []interface{}{h,h.Glasses,Window{}}
for _,o := range objectsInProximity {
shatter(o)
}
}
func shatter(i interface{}) {
s, ok := i.(Shatterable)
if ok {
fmt.Printf("shattering a %T\n", s)
s.shatter()
}
}
$ go run a.go
shattering a main.Human
shattering a main.Glasses
shattering a main.Window
As mentioned in this thread:
We're talking about anonymous fields of a struct
(http://golang.org/ref/spec#Struct_types).
(modified version, as the term superset is confusing)
A struct with an anonymous field satisfies every interface with all the interface methods declared by the anonymous field or the struct itself.
type Human struct { Glasses }
Since Glasses can be shattered, Human also satisfy the same interface.
Note: embedding anonymous field in a struct is the closest to "inheritance", even though the answer to "Golang: what's the point of interfaces when you have multiple inheritance" reminds us that:
Go doesn't have inheritance.
If Man 'extended' Human (by having it as an anonymous field), any method that used Human as an argument, would not be able to take Man as an argument.
(That means here Human extends... Glasses?! That might show some kind of design imperfection)
I explained before in "If struct A is embedded in B, can methods on A access method and fields of B?" that this isn't true sub-typing.
Interfaces enable functions to have a 'placeholder' parameter which can take different structs as an argument.
Here, if Human isn't supposed to be shattered, it shouldn't include the anonymous field Glasses.
I am starting studying OOP and I want to learn what constitutes a class. I am a little confused at how loosely some core elements are being used and thus adding to my confusion.
I have looked at the C++ class, the java class and I want to know enough to write my own pseudo class to help me understand.
For instance in this article I read this (.. class attribute (or class property, field, or data member)
I have seen rather well cut out questions that show that there is a difference between class property and class field for instance What is the difference between a Field and a Property in C#?
Depending on what language I am studying, is the definition of
Property
Fields
Class variables
Attributes
different from language to language?
"Fields", "class variables", and "attributes" are more-or-less the same - a low-level storage slot attached to an object. Each language's documentation might use a different term consistently, but most actual programmers use them interchangeably. (However, this also means some of the terms can be ambiguous, like "class variable" - which can be interpreted as "a variable of an instance of a given class", or "a variable of the class object itself" in a language where class objects are something you can manipulate directly.)
"Properties" are, in most languages I use, something else entirely - they're a way to attach custom behaviour to reading / writing a field. (Or to replace it.)
So in Java, the canonical example would be:
class Circle {
// The radius field
private double radius;
public Circle(double radius) {
this.radius = radius;
}
// The radius property
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
// We're doing something else besides setting the field value in the
// property setter
System.out.println("Setting radius to " + radius);
this.radius = radius;
}
// The circumference property, which is read-only
public double getCircumference() {
// We're not even reading a field here.
return 2 * Math.PI * radius;
}
}
(Note that in Java, a property foo is a pair of accessor methods called getFoo() and setFoo() - or just the getter if the property is read-only.)
Another way of looking at this is that "properties" are an abstraction - a promise by an object to allow callers to get or set a piece of data. While "fields" etc. are one possible implementation of this abstraction. The values for getRadius() or getCircumference() in the above example could be stored directly, or they could be calculated, it doesn't matter to the caller; the setters might or might not have side effects; it doesn't matter to the caller.
I agree with you, there's a lot of unnecessary confusion due to the loose definitions and inconsistent use of many OO terms. The terms you're asking about are used somewhat interchangeably, but one could say some are more general than others (descending order): Property -> Attributes -> Class Variables -> Fields.
The following passages, extracted from "Object-Oriented Analysis and Design" by Grady Booch help clarify the subject. Firstly, it's important to understand the concept of state:
The state of an object encompasses all of the (usually static) properties of the object plus the current (usually dynamic) values of each of these properties. By properties, we mean the totality of the object's attributes and relationships with other objects.
OOP is quite generic regarding certain nomenclature, as it varies wildly from language to language:
The terms field (Object Pascal), instance variable (Smalltalk), member object (C++), and slot (CLOS) are interchangeable, meaning a repository for part of the state of an object. Collectively, they constitute the object's structure.
But the notation introduced by the author is precise:
An attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class. Using the language-independent syntax, an attribute may have a name, a class, or both, and optionally a default expression: A:C=E.
Class variable: Part of the state of a class. Collectively, the class variables of a class constitute its structure. A class variable is shared by all instances of the same class. In C++, a class variable is declared as a static member.
In summary:
Property is a broad concept used to denote a particular characteristic of a class, encompassing both its attributes and its relationships to other classes.
Attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class.
Class variable is an attribute defined in a class of which a single copy exists, regardless of how many instances of the class exist. So all instances of that class share its value as well as its declaration.
Field is a language-specific term for instance variable, that is, an attribute whose value is specific to each object.
I've been doing oop for more than 20 years, and I find that people often use different words for the same things. My understanding is that fields, class variables and attributes all mean the same thing. However, property is best described by the stackoverflow link that you included in your question.
Generally fields, methods, static methods, properties, attributes and class (or static variables) do not change on a language basis... Although the syntax will probably change on a per language basis, they will be function in the way you would expect across languages (expect terms like fields/data members to be used interchangably across languages)
In C#....
A field is a variable that exists for a given instance of a class.
eg.
public class BaseClass
{
// This is a field that might be different in each instance of a class
private int _field;
// This is a property that accesses a field
protected int GetField
{
get
{
return _field;
}
}
}
Fields have a "visibility" this determines what other classes can see the field, so in the above example a private field can only be used by the class that contains it, but the property accessor provides readonly access to the field by subclasses.
A property lets you get (sometimes called an accessor) or set (sometimes called a mutator) the value of field... Properties let you do a couple of things, prevent writing a field for example from outside the class, change the visibility of the field (eg private/protected/public). A mutator allows you to provide some custom logic before setting the value of a field
So properties are more like methods to get/set the value of a field but provide more functionality
eg.
public class BaseClass
{
// This is a field that might be different in each instance of a class
private int _field;
// This is a property that accesses a field, but since it's visibility
// is protected only subclasses will know about this property
// (and through it the field) - The field and property in this case
// will be hidden from other classes.
protected int GetField
{
// This is an accessor
get
{
return _field;
}
// This is a mutator
set
{
// This can perform some more logic
if (_field != value)
{
Console.WriteLine("The value of _field changed");
_field = value;
OnChanged; // Call some imaginary OnChange method
} else {
Console.WriteLine("The value of _field was not changed");
}
}
}
}
A class or static variable is a variable which is the same for all instances of a class..
So, for example, if you wanted a description for a class that description would be the same for all instance of the class and could be accessed by using the class
eg.
public class BaseClass
{
// A static (or class variable) can be accessed from anywhere by writing
// BaseClass.DESCRIPTION
public static string DESCRIPTION = "BaseClass";
}
public class TestClass
{
public void Test()
{
string BaseClassDescription = BaseClass.DESCRIPTION;
}
}
I'd be careful when using terminology relating to an attribute. In C# it is a class that can be applied to other classes or methods by "decorating" the class or method, in other context's it may simply refer to a field that a class contains.
// The functionality of this attribute will be documented somewhere
[Test]
public class TestClass
{
[TestMethod]
public void TestMethod()
{
}
}
Some languages do not have "Attributes" like C# does (see above)
Hopefully that all makes sense... Don't want to overload you!
Firstly, you need to select a language. For example, I would recommend you to select Ruby language and community. Until you select a language, you cannot escape confusion, as different communities use different terms for the same things.
For example, what is known as Module in Ruby, Java knows as abstract class. What is known as attributes in some languages, is known as instance variables in Ruby. I recommend Ruby especially for its logical and well-designed OOP system.
Write the following in a *.rb file, or on the command line in irb (interactive Ruby interpreter):
class Dog # <-- Here you define a class representing all dogs.
def breathe # <-- Here you teach your class a method: #breathe
puts "I'm breathing."
end
def speak # <-- Here you teach your class another method: #speak
puts "Bow wow!"
end
end
Now that you have a class, you can create an instance of it:
Seamus = Dog.new
You have just created an instance, a particular dog of class Dog, and stored it in the constant Seamus. Now you can play with it:
Seamus.breathe # <-- Invoking #breathe instance method of Seamus
#=> I'm breathing.
Seamus.speak # <-- Invoking #speak instance method of Seamus
#=> Bow wow!
As for your remaining terminology questions, "property" or "attribute" is understood as "variable" in Ruby, almost always an instance variable. And as for the term "data member", just forget about it. The term "field" is not really used in Ruby, and "class variable" in Ruby means something very rarely used, which you definitely don't need to know at this moment.
So, to keep the world nice and show you that OOP is really simple and painless in Ruby, let us create an attribute, or, in Ruby terminology, an instance variable of Dog class. As we know, every dog has some weight, and different dogs may have different weights. So, upon creation of a new dog, we will require the user to tell us dog's weight:
class Dog
def initialize( weight ) # <-- Defining initialization method with one argument 'weight'
#weight = weight # <-- Setting the dog's attribute (instance variable)
end
attr_reader :weight # <-- Making the dog's weight attribute visible to the world.
end
Drooly = Dog.new( 16 ) # <-- Weight now must provide weight upon initialization.
Drooly.weight # <-- Now we can ask Drooly about his weight.
#=> 16
Remember, with Ruby (or Python), things are simple.
I discovered in my question that Properties as defined in .Net are just a convenience syntax for code, and they are not tied to underlying variables at all (except for Auto-Implemented Properties, of course). So, saying "what is the difference between class property and class field" is like saying: what is the difference between a method and an attribute. No difference, one is code and the other is data. And, they need not have anything to do with each other.
It is really too bad that the same words, like "attribute" and "property", are re-used in different languages and ideologies to have starkly different meanings. Maybe someone needs to define an object-oriented language to talk about concepts in OOP? UML?
In The Class
public class ClassSample
{
private int ClassAttribute;
public int Property
{
get { return ClassAttribute; }
set { ClassAttribute = value; }
}
}
In the Program
class Program
{
static void Main(string[] args)
{
var objectSample = new ClassSample();
//Get Object Property
var GetProperty = objectSample.Property;
}
}