Search Results

Search found 597 results on 24 pages for 'constructors'.

Page 2/24 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Why Java interfaces can't have constructors?

    - by AndrejaKo
    This question showed up on my mid-term exams and I've been searching for correct answer for some time. I know that Java interfaces can't be directly instantiated so they don't need constructors and that they can have only public static final attributes so they don't need constructors to set them up but that's not the expected answer.

    Read the article

  • Requriing static class setter to be called before Constructor, bad design?

    - by roverred
    I have a class, say Foo, and every instance of Foo will need and contain the same List object, myList. Since every class instance will share the same List Object, I thought it would be good to make myList static and use a static function to set myList before the constructor is called. I was wondering if this was bad, because this requires the setter to be called before the constructor. If the person doesn't, the program will crash. Alternative way would be passing myList every time. Thanks.

    Read the article

  • Custom constructors for models in Google App Engine (python)

    - by Nikhil Chelliah
    I'm getting back to programming for Google App Engine and I've found, in old, unused code, instances in which I wrote constructors for models. It seems like a good idea, but there's no mention of it online and I can't test to see if it works. Here's a contrived example, with no error-checking, etc.: class Dog(db.Model): name = db.StringProperty(required=True) breeds = db.StringListProperty() age = db.IntegerProperty(default=0) def __init__(self, name, breed_list, **kwargs): db.Model.__init__(**kwargs) self.name = name self.breeds = breed_list.split() rufus = Dog('Rufus', 'spaniel terrier labrador') rufus.put() The **kwargs are passed on to the Model constructor in case the model is constructed with a specified parent or key_name, or in case other properties (like age) are specified. This constructor differs from the default in that it requires that a name and breed_list be specified (although it can't ensure that they're strings), and it parses breed_list in a way that the default constructor could not. Is this a legitimate form of instantiation, or should I just use functions or static/class methods? And if it works, why aren't custom constructors used more often?

    Read the article

  • Design by contracts and constructors

    - by devoured elysium
    I am implementing my own ArrayList for school purposes, but to spice up things a bit I'm trying to use C# 4.0 Code Contracts. All was fine until I needed to add Contracts to the constructors. Should I add Contract.Ensures() in the empty parameter constructor? public ArrayList(int capacity) { Contract.Requires(capacity > 0); Contract.Ensures(Size == capacity); _array = new T[capacity]; } public ArrayList() : this(32) { Contract.Ensures(Size == 32); } I'd say yes, each method should have a well defined contract. On the other hand, why put it if it's just delegating work to the "main" constructor? Logicwise, I wouldn't need to. The only point I see where it'd be useful to explicitly define the contract in both constructors is if in the future we have Intelisense support for contracts. Would that happen, it'd be useful to be explicit about which contracts each method has, as that'd appear in Intelisense. Also, are there any books around that go a bit deeper on the principles and usage of Design by Contracts? One thing is having knowledge of the syntax of how to use Contracts in a language (C#, in this case), other is knowing how and when to use it. I read several tutorials and Jon Skeet's C# in Depth article about it, but I'd like to go a bit deeper if possible. Thanks

    Read the article

  • How to get the parameter names of an object's constructors (reflection)?

    - by Tom
    Say I somehow got an object reference from an other class: Object myObj = anObject; Now I can get the class of this object: Class objClass = myObj.getClass(); Now, I can get all constructors of this class: Constructor[] constructors = objClass.getConstructors(); Now, I can loop every constructor: if (constructors.length > 0) { for (int i = 0; i < constructors.length; i++) { System.out.println(constructors[i]); } } This is already giving me a good summary of the constructor, for example a constructor public Test(String paramName) is shown as public Test(java.lang.String) Instead of giving me the class type however, I want to get the name of the parameter.. in this case "paramName". How would I do that? I tried the following without success: if (constructors.length > 0) { for (int iCon = 0; iCon < constructors.length; iCon++) { Class[] params = constructors[iCon].getParameterTypes(); if (params.length > 0) { for (int iPar = 0; iPar < params.length; iPar++) { Field fields[] = params[iPar].getDeclaredFields(); for (int iFields = 0; iFields < fields.length; iFields++) { String fieldName = fields[i].getName(); System.out.println(fieldName); } } } } } Unfortunately, this is not giving me the expected result. Could anyone tell me how I should do this or what I am doing wrong? Thanks!

    Read the article

  • Jython saying "No visible constructors for class"

    - by clutch
    I have a jython servlet as part of a large application running in tomcat5. I tested a few Spring Framework classes and create the objects in the Jython servlet. When I try to create objects of classes in the application I catch an Exception message "No visible constructors for class". These java classes do have a public constructor class, such as: public SchoolImpl() { } I create the object in python: from com.dc.sports.entity import SchoolImpl ... school = SchoolImpl() What am I doing wrong?

    Read the article

  • Injection of class with multiple constructors

    - by Jax
    Resolving a class that has multiple constructors with NInject doesn't seem to work. public class Class1 : IClass { public Class1(int param) {...} public Class1(int param2, string param3) { .. } } the following doesn’t seem to work: IClass1 instance = IocContainer.Get<IClass>(With.Parameters.ConstructorArgument(“param”, 1)); The hook in the module is simple, and worked before I added the extra constructor: Bind().To(); Thanks in advance...

    Read the article

  • Purpose of PHP constructors

    - by Bharanikumar
    Hi, I am working with classes and object class structure, but not at a complex level – just classes and functions, then, in one place, instantiation. As to __construct and __destruct, please tell me very simply: what is the purpose of constructors and destructors? I know the school level theoretical explanation, but i am expecting something like in real world, as in which situations we have to use them. Provide also an example, please. Regards

    Read the article

  • ImmutableDictionary has no constructors defined

    - by lukasLansky
    So, I would like to write something like this: var d = new ImmutableDictionary<string, int> { { "a", 1 }, { "b", 2 } }; (using ImmutableDictionary from System.Collections.Immutable). It seems like a straightforward usage as I am declaring all the values upfront -- no mutation there. But this gives me error: The type 'System.Collections.Immutable.ImmutableDictionary<TKey,TValue>' has no constructors defined How I am supposed to create a new immutable dictionary with static content?

    Read the article

  • Higher-order type constructors and functors in Ocaml

    - by sdcvvc
    Can the following polymorphic functions let id x = x;; let compose f g x = f (g x);; let rec fix f = f (fix f);; (*laziness aside*) be written for types/type constructors or modules/functors? I tried type 'x id = Id of 'x;; type 'f 'g 'x compose = Compose of ('f ('g 'x));; type 'f fix = Fix of ('f (Fix 'f));; for types but it doesn't work. Here's a Haskell version for types: data Id x = Id x data Compose f g x = Compose (f (g x)) data Fix f = Fix (f (Fix f)) -- examples: l = Compose [Just 'a'] :: Compose [] Maybe Char type Natural = Fix Maybe -- natural numbers are fixpoint of Maybe n = Fix (Just (Fix (Just (Fix Nothing)))) :: Natural -- n is 2 -- up to isomorphism composition of identity and f is f: iso :: Compose Id f x -> f x iso (Compose (Id a)) = a

    Read the article

  • what possible workarounds are there for "only parameterless constructors are support in Linq to Enti

    - by Ralph Shillington
    In my query I need to return instances of a class that doesn't have a default constructor (specifically this is in a custom Membership provider, and MembershipUser is the culprit) var users = from l in context.Logins select new MembershipUser( Name, l.Username, // username l.Id, // provider key l.MailTo, l.PasswordQuestion, l.Notes.FirstOrDefault().NoteText, l.IsApproved, l.IsLockedOut, l.CreatedOn, l.LastLoginOn.HasValue ? l.LastLoginOn.Value : DateTime.MinValue, l.LastActivityOn.HasValue ? l.LastActivityOn.Value : DateTime.MinValue, DateTime.MinValue, l.LastLockedOutOn.HasValue ? l.LastLockedOutOn.Value : DateTime.MinValue ); is syntacitally correct, but results in a runtime error as Only parameterless constructors and initializers are supported in LINQ to Entities.

    Read the article

  • By-Name-Parameters for Constructors

    - by hotzen
    Hello, coming from my other question is there a way to get by-name-parameters for constructors working? I need a way to provide a code-block which is executed on-demand/lazy/by-name inside an object and this code-block must be able to access the class-methods as if the code-block were part of the class. Following Testcase fails: package test class ByNameCons(code: => Unit) { def exec() = { println("pre-code") code println("post-code") } def meth() = println("method") def exec2(code2: => Unit) = { println("pre-code") code2 println("post-code") } } object ByNameCons { def main(args: Array[String]): Unit = { val tst = new ByNameCons { println("foo") meth() // knows meth() as code is part of ByNameCons } tst.exec() // ByName fails (executed right as constructor) println("--------") tst.exec2 { // ByName works println("foo") //meth() // does not know meth() as code is NOT part of ByNameCons } } } Output: foo method pre-code post-code -------- pre-code foo post-code

    Read the article

  • Use of Java constructors in persistent entities

    - by Mr Morgan
    Hello I'm new to JPA and using persistence in Java anyway and I have two questions I can't quite work out: I have generated tags as: @JoinColumn(name = "UserName", referencedColumnName = "UserName") @ManyToOne(optional = false) private User userName; @JoinColumn(name = "DatasetNo", referencedColumnName = "DatasetNo") @ManyToOne(optional = false) private Dataset datasetNo; But in one of the constructors for the class, no reference is made to columns UserName or DatasetNo whereas all other columns in the class are referenced in the constructor. Can anyone tell me why this is? Both columns UserName and DatasetNo are 'foreign keys' on the entity Visualisation which corresponds to a database table of the same name. I can't quite work out the ORM. And when using entity classes, or POJO, is it better to have class variables like: private User userName; Where an instance of a class is specified or simply the key of that class instance like: private String userName; Thanks Mr Morgan.

    Read the article

  • Using free function as pseudo-constructors to exploit template parameter deduction

    - by Poita_
    Is it a common pattern/idiom to use free functions as pseudo-constructors to avoid having to explicitly specify template parameters? For example, everyone knows about std::make_pair, which uses its parameters to deduce the pair types: template <class A, class B> std::pair<A, B> make_pair(A a, B b) { return std::pair<A, B>(a, b); } // This allows you to call make_pair(1, 2), // instead of having to type pair<int, int>(1, 2) // as you can't get type deduction from the constructor. I find myself using this quite often, so I was just wondering if many other people use it, and if there is a name for this pattern?

    Read the article

  • Designing constructors around type erasure in Java

    - by Internet Friend
    Yesterday, I was designing a Java class which I wanted to be initalized with Lists of various generic types: TheClass(List<String> list) { ... } TheClass(List<OtherType> list) { ... } This will not compile, as the constructors have the same erasure. I just went with factory methods differentiated by their names instead: public static TheClass createWithStrings(List<String> list) public static TheClass createWithOtherTypes(List<OtherType> list) This is less than optimal, as there isn't a single obvious location where all the different options for creating instances are available. I tried to search for better design ideas, but found surprisingly few results. What other patterns exist for designing around this problem?

    Read the article

  • prevent using functions before initialization, constructors-like in C

    - by Hernán Eche
    This is the way I get to prevent funA,funB,funC, etc.. for being used before init #define INIT_KEY 0xC0DE //any number except 0, is ok static int initialized=0; int Init() { //many init task initialized=INIT_KEY; } int funA() { if (initialized!=INIT_KEY) return 1 //.. } int funB() { if (initialized!=INIT_KEY) return 1 //.. } int funC() { if (initialized!=INIT_KEY) return 1 //.. } The problem with this approach is that if some of those function is called within a loop so "if (initialized!=INIT_KEY)" is called again, and again, although it's not necessary. It's a good example of why constructors are useful haha, If it were an object I would be sure that when was created initialization was called, but in C, I don't know how to do it. Any other ideas are welcome!

    Read the article

  • Can C++ Constructors be templates?

    - by Gokul
    Hi, I have non-template class with a templatized constructor. This code compiles for me. But i remember that somewhere i have referred that constructors cannot be templates. Can someone explain whether this is a valid usage? typedef double Vector; //enum Method {A, B, C, D, E, F}; struct A {}; class Butcher { public: template <class Method> Butcher(Method); private: Vector a, b, c; }; template <> Butcher::Butcher(struct A) : a(2), b(4), c(2) { // a = 0.5, 1; // b = -1, 1, 3, 2; // c = 0, 1; } Thanks, Gokul.

    Read the article

  • variadic constructors

    - by FredOverflow
    Are variadic constructors supposed to hide the implicitly generated ones, i.e. the default constructor and the copy constructor? struct Foo { template<typename... Args> Foo(Args&&... x) { std::cout << "inside the variadic constructor\n"; } }; int main() { Foo a; Foo b(a); } Somehow I was expecting this to print nothing after reading this answer, but it prints inside the variadic constructor twice on g++ 4.5.0 :( Is this behavior correct?

    Read the article

  • Question About NerdDinner Controller Constructors

    - by Gavin Draper
    I've been looking at the Nerd Dinner app, more specifically how it handles its unit tests. The following constructors for the RSVPController are confusing my slightly public RSVPController() : this(new DinnerRepository()) { } public RSVPController(IDinnerRepository repository) { dinnerRepository = repository; } From what I can tell the second one is used by the unit tests so it can use Fake repositories. What I cant work out is what the first constructor does. It doesn't seem to ever set the dinnerRepository variable, it seems to imply its inheriting from something but I really don't get it. Can anyone explain? Thanks

    Read the article

  • Constructors + Dependency Injection

    - by Sunny
    If I am writing up a class with more than 1 constructor parameter like: class A{ public A(Dependency1 d1, Dependency2 d2, ...){} } I usually create a "argument holder"-type of class like: class AArgs{ public Dependency1 d1 { get; private set; } public Dependency2 d2 { get; private set; } ... } and then: class A{ public A(AArgs args){} } Typically, using a DI-container I can configure the constructor for dependencies & resolve them & so there is minimum impact when the constructors need to change. Is this considered an anti-pattern and/or any arguments against doing this?

    Read the article

  • Constructors and method chaining in JavaScript

    - by Sethen Maleno
    I am trying to make method chaining work in conjunction with my constructors, but I am not exactly sure how to go about it. Here is my code thus far: function Points(one, two, three) { this.one = one; this.two = two; this.three = three; } Points.prototype = { add: function() { return this.result = this.one + this.two + this.three; }, multiply: function() { return this.result * 30; } } var some = new Points(1, 1, 1); console.log(some.add().multiply()); I am trying to call the multiply method on the return value of the add method. I know there is something obvious that I am not doing, but I am just not sure what it is. Any thoughts?

    Read the article

  • java: can't use constructors in abstract class

    - by ufk
    Hi. I created the following abstract class for job scheduler in red5: package com.demogames.jobs; import com.demogames.demofacebook.MysqlDb; import org.red5.server.api.IClient; import org.red5.server.api.IConnection; import org.red5.server.api.IScope; import org.red5.server.api.scheduling.IScheduledJob; import org.red5.server.api.so.ISharedObject; import org.apache.log4j.Logger; import org.red5.server.api.Red5; /** * * @author ufk */ abstract public class DemoJob implements IScheduledJob { protected IConnection conn; protected IClient client; protected ISharedObject so; protected IScope scope; protected MysqlDb mysqldb; protected static org.apache.log4j.Logger log = Logger .getLogger(DemoJob.class); protected DemoJob (ISharedObject so, MysqlDb mysqldb){ this.conn=Red5.getConnectionLocal(); this.client = conn.getClient(); this.so=so; this.mysqldb=mysqldb; this.scope=conn.getScope(); } protected DemoJob(ISharedObject so) { this.conn=Red5.getConnectionLocal(); this.client=this.conn.getClient(); this.so=so; this.scope=conn.getScope(); } protected DemoJob() { this.conn=Red5.getConnectionLocal(); this.client=this.conn.getClient(); this.scope=conn.getScope(); } } Then i created a simple class that extends the previous one: public class StartChallengeJob extends DemoJob { public void execute(ISchedulingService service) { log.error("test"); } } The problem is that my main application can only see the constructor without any parameters. with means i can do new StartChallengeJob() why doesn't the main application sees all the constructors ? thanks!

    Read the article

  • In Java it seems Public constructors are always a bad coding practice

    - by Adam Gent
    This maybe a controversial question and may not be suited for this forum (so I will not be insulted if you choose to close this question). It seems given the current capabilities of Java there is no reason to make constructors public ... ever. Friendly, private, protected are OK but public no. It seems that its almost always a better idea to provide a public static method for creating objects. Every Java Bean serialization technology (JAXB, Jackson, Spring etc...) can call a protected or private no-arg constructor. My questions are: I have never seen this practice decreed or written down anywhere? Maybe Bloch mentions it but I don't own is book. Is there a use case other than perhaps not being super DRY that I missed? EDIT: I explain why static methods are better. .1. For one you get better type inference. For example See Guava's http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained .2. As a designer of the class you can later change what is returned with a static method. .3. Dealing with constructor inheritance is painful especially if you have to pre-calculate something.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >