I have a widget that takes a number representing pages allowed to be displayed on the screen.
If the device is weak a bool can be passed that overrides the initial value.
However, since all values are final I must evaluate it in the constructor before the value is set.
class _A extends StatefullWidget{
_A(this.limitPages,
this.pagesToDisplay: limitPages ? 10 : pagesToDisplay,
)
final int pagesToDisplay;
final bool limitPages;
}
I could declare it in the initializer list, but then I can't pass an argument for pagesToDisplay.
class _A extends StatefullWidget{
_A(this.limitPages)
:this.pagesToDisplay: limitPages ? 10 : pagesToDisplay
final int pagesToDisplay;
final bool limitPages;
}
Is there any way to assert a statement in/before the constructor sets the final value?
If you want to use a parameter in the initializer list, the parameter can't be an initializing parameter, and you need to do the initializing in the initializer list instead:
class _A {
_A(bool limitPages, int pagesToDisplay)
: limitPages = limitPages,
pagesToDisplay = limitPages ? 10 : pagesToDisplay;
final int pagesToDisplay;
final bool limitPages;
}
public class Square {
private double sideLength;
public double GetArea() {
return sideLength * sideLength;
}
public double GetSideLength() {
return sideLength;
}
}
Can you tell me how to write a no-arg constructor for this class. The constructor should assign
the sideLength field the value 0.0.
First I think this is a very basic question, you must google it before asking here, though now you already asked, I try to answer it here as in the begging it's really tough to actually find the correct answer.
public Square (){
this.sideLength = 0.0;
}
As when you create a class java add a default constructor for you which is also no-args constructor, but you can always redefine and implement it.
You can refer this for more detail :
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
my code is like this
public class B {
public B(int f) {
}
}
public class A extends B{
int f=4;
public A() {
super(f);
}
}
why does it make a compile error?
In order to create an instance of class A, Java will behave as if it first creates an instance of B, meaning that the constructor of the super class, super(), will be called, (or in this case, you call it yourself) and then "adding on" the attributes of class A.
This is also why a super() call always has to be the first instruction in a constructor.
You are trying to pass an argument, which in a sense doesn't exist yet, because you try to read f before you called super().
What you could do is the following:
public class A extends B {
static final int F_CONST = 4;
int f = F_CONST;
public A() {
super(F_CONST);
}
}
Here F_CONST is a constant "static" variable, which is a "class variable", instead of an "object or instance variable". static members will be initialized when the class is loaded in memory, which is before any constructor can be called. The compiler is even allowed to replace F_CONST with just the value 4 directly, which would also be a simple solution.
I have an AS3 Singleton:
package
{
public class Singleton
{
public function Singleton(enforcer:SingletonEnforcer):void
{
if(!enforcer){throw new Error("Only one instance of Singleton Class allowed.");}
}
private static var _instance:Singleton;
public static function getInstance():Singleton
{
if(!Singleton._instance)
{
Singleton._instance=new Singleton(new SingletonEnforcer());
}
return Singleton._instance;
}
}
}
class SingletonEnforcer{}
Consider prop and func() to be a property and method respectively of the Singleton class.
How should I access them?
1. Make them static and use this:
Singleton.getInstance();
Singleton.prop;
Singleton.func();
2. Not make them static and use this:
Singleton.getInstance().prop;
Singleton.getInstance().func();
Does it matter, or is it just visual prefference?
Thank you.
The reason to use a singleton instance is so that you can have class members used in a (relatively) static way.
I won't get into the arguments over whether or not to use a singleton here, there's a very long debate over whether it's a good pattern or not.
Typically, when singletons are used, you store access to them in a local variable and use them like any other class instance. The primary difference, is instead of using:
foo = new Foo();
You use:
foo = Foo.instance;
//Actionscript supports properties which makes this a self-initializing call
-or-
foo = Foo.getInstance();
Followed by
foo.bar();
foo.baz();
foo.fizz = 'buzz';
This doesn't mean that Foo can't have static members of the class, but the rules for adding static members on a Singleton are the same for adding static members to any other class. If the function belongs to the instance, it should be used on the instance, if it belongs to the class, it should be static.
I'm trying to figure out when it would be appropriate for a class to have both static and non-static functions. AKA:
$obj = new ClassA;
$obj->doOOPStuff();
$something = ClassA::doStaticStuff();
Note: This example is done in PHP, however the question is language agnostic .
It seems that if you have a class that is meant to be instantiated, any functions that can be called statically, most likely belong in another class.
Is there any viable cases where I would have a class that used static AND non-static members?
One example: when Creation has to happen in a specific way.
class Foo {
public:
static Foo* Create(...params...);
private:
Foo();
};
Consider String class in .NET. It contains a non-static Split method which breaks some instance into a string[] and a static Join method, which takes a string[] and transform it into a string again.
A static method is applicable when you don't need to keep any state. So Math.Sin() just depends on its parameters and, given same parameters, output will always be the same. A non-static method can have different behavior is called multiple times, as it can keep a internal state.
If the functionality provided by static methods is relevant to that class and its objects, why not. It is pretty common.
Static method are most often factory methods
public class MyClass {
public static MyClass createMyClass(int a, double b) {..}
public static MyClass createSubclassOfMyClass(int c, boolean cond) {..}
public int calculateThis();
public double calculateThat();
}
Another use is to access some property that is logically bound that that class, but not separately to instances. For example - a cache:
(Note - of course synchronization should be taken into account in this example)
public class MyClass {
public static final Cache cache = new Cache();
public static void putInCacheIfNeeded(Object obj) {..}
public static void replaceInCache(Object obj) {..}
public void doSomethingCacheDependend(Object obj) {
if (something) {
MyClass.putInCacheIfNeeded(obj);
} else {
MyClass.replaceInCache(obj);
}
}
}
(Java language for the examples)
Imagine your constructor has two overloads that both are strings:
public class XmlDocument
{
public static XmlDocument CreateFromFile(string filePath);
public static XmlDocument CreateFromXml(string xml);
}
The static function can provide meaningful name to the constructor.
$dialog = DialogFoo::createOpenDialog();
$dialog = DialogFoo::createDocumentOpenDialog();
$dialog = DialogFoo::createImageOpenDialog();
It could also be used to enforce Singleton pattern.
$dialog = DialogFoo::getInstance()
Static class members are most useful where everything must either be in an object or be in a global scope; they are less useful in a language such as Python that supports module-level scopes.
I use static methods to instantiate new objects when I dont want the to give access to the constructor. I ensure that any necessary preconditions are carried out on the class before creating and object. In this example I have a counter to return how many objects are created, if I have 10 objects I prevent any more from being instantiated.
class foo {
private:
static int count;
foo() {}
public:
static foo bar() {
count++;
if (count<=10){
return new foo;
} else {
return null;
}
Let's assume a class has instance methods, here are some good use case for having static methods too:
For static utility methods
Such methods apply to any instance, for example String.format(String, Object...) in Java.
Use them when you don't want to create a specific instance for the job.
For static factory methods
Factory methods are methods that simply instantiate objects like the getInstance() and valueOf() methods in the Java API. getInstance() is the conventional instantiation method in singletons while valueOf() are often type-conversion methods, like in String.valueOf(int).
Use them to improve performance via object-caching, in interface-based frameworks (like the Collections Framework in Java) where you may want to return a subtype, to implement singletons (cough).
In general, static functions produce functionality highly related to class itself. It may be some helper functions, factory methods etc. In this case all functionality contains in one place, it correspond to DRY principle, increases cohesion and reduces coupling.