FAQ Database Discussion Community


Making list of objects of class with function overloading

c++,oop
I am having a class Car, now I want to make linked list of Car objects. So for this I am having a Node class to hold data for each node. class StringOfCar; class Node { private: Node* next; Car* data; Node () { next = 0; data = 0;...

Am I violating the Object-Oriented encapsulation principle? [closed]

javascript,oop
I was wondering whether this would be a correct way to initialize an object, which requires a random position and speed on the map. I am not sure whether I am violating the encapsulation principle with the object initializers this.x and thi.y by calling Warrior.chooseX() and Warrior.choosey(), respectively. var Warrior...

Rails modeling headache

ruby-on-rails,oop,models
I am in the process of building a Rails app that will let logged-in users: create multiple agendas access each agenda through a "month" view add events to each month share each agenda (through a link) with other logged-in users, who will see it with the same default "month" view...

Switching Classes during __construct()

php,class,oop,constructor,magic-methods
Let's take the following classes for a moment: class member { public $id; public function __construct($id) { $this->id = $id; // Check user level if ($this->check_user_level() == moderator) { $this = new moderator($this->id); } } private function check_user_level() { // Return user level from system based on user ID }...

Having issues with methods

java,oop,methods,constructor
Alright, I have a class assignment to create 3 predetermined methods for a rock, paper, scissors program written by the teacher. However, when I run the program it running the methods multiple times in a row. I've looked through the code several times and can't figure out the problem. Below...

mysqli_query() expects parameter 1 to be mysqli, i cant use a variable?

php,oop,mysqli
index.php <?php if(!defined('ROOT')) { define('ROOT','C:/Apache/htdocs/website/inc'); } require_once ROOT. '/config/db.php'; require_once ROOT. '/library/classes/class.User.php'; $checkUser = new userFunction(); if($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_POST["username"]; $password = $_POST["password"]; $user = $checkUser->userLogin($username, $password); if($user) { echo "Succes"; } else { echo "Failed"; } } db.php <?php class dbConnect { function __construct() { require_once('config.php');...

JavaScript oop: Designing classes correctly

javascript,oop,closures,prototype
Taking this list of similar questions: How to set up JavaScript namespace and classes properly Javascript namespace declaration with function-prototype Best OOP approach to these two small JavaScript classes I'd concluded there are two possible ways for implementing classes and instances in JS: using an inner function or using a...

Force a child class to initialise a parent property after computation

c#,oop
I have a child class Bicycle that inherits from Agent. The agent has a property which depends on the bicycle to define it. Namely, the physics model for the agent needs to be initialised with the velocity and acceleration constraints which are defined on a per-bicycle-basis and would be different...

How access member function from arrayobject in a loop

c++,oop
I am trying to access public function get_data(), to generate an output "here ", to see if creating dynamic object from array of object..so how can i do that. #include<iostream> #include <conio.h> using namespace std; int counts = 0; int no_of_array; class Matrix { int **dynamicArray; public: Matrix() { counts++;...

Why can't I call a method I define in a field? [duplicate]

java,oop,methods
This question already has an answer here: Calling newly defined method from anonymous class 5 answers Consider the following code. B.java public class B { void foo() { System.out.println("foo"); } } A.java public class A { B b = new B() { void lorem() { System.out.println("Lorem"); } }; void...

Calling a method on array iteration, from an object - PHP

php,arrays,oop
What I'm trying to do, is iterate through an array (Which in my case is a MySql result), and output it, but also do something else with the data at the same. Doing this using procedural methods is easy - just put it in the foreach loop. But, I'm wondering...

Is array of primitives assigned to variable as an Object (by reference) or by value?

java,arrays,oop
I am writing a class of Polygon and after thinking about it I decided to use arrays of x and y values and save the dots. This led me to think, out of laziness, about this: int[] x, y; x = y = new int[NUM]; I know that arrays are...

PHP classes - is it preferable to use normal variables instead of properties?

php,class,oop
For my latest website I’ve been trying to use classes. Mainly to teach myself more about OOP and learn through experience. Whenever I needed a ‘variable’ within my class I created a property, for instance: class someClass { var $valueToUseHere; // Only used internally - can I just use a...

Calling on an implemented method automatically?

java,oop,implementation
I was curious about how the implements keyword works, and I was hoping someone could explain to me, where does the implemented method get called on? For example let's say I have a class that implements ActionListener. It now implements the public void actionPerformed(ActionEvent e) { } method. I have...

How Do I Architect Out This Relationship

sql,oop
The best way I can describe this is with an example: Imagine Many Businesses. In any one business there can be multiple divisions. In each division there can be multiple dept. This would be a series of 1 to many, right?...But now what if a given dept can be elevated...

Interfaces in UML component diagram

oop,uml
In the UML class diagram the interface is equivalent to the interface concept in programming languages (a set of methods that the class that implement the interface should implement). I want to know if the interface in the component diagram has the same meaning. Are the interfaces mentioned in the...

How to reuse this ViewController code in an object oriented way?

ios,objective-c,oop
I have an app with four viewControllers, and there is a lot of code that is repeating exactly the same way in the four view controllers, and I would like to know what is the best OOP way to write this code only one time and reuse it in the...

Automatic cast to subclass in getter/setter

java,oop
I have a rather weird question. Consider the following two classes: public class Node<T> { private Node<T> parent; private Node<T> left; private Node<T> right; private T data; public Node(Node<T> parent, T data) { this.parent = parent; this.data = data; } public Node<T> getParent() { return parent; } public void setParent(Node<T>...

Can adhering to the JavaBeans naming standard aid in achieving encapsulation?

java,oop,inheritance,coupling,cohesion
Is it possible that java beans naming standards help in achieving encapsulation? Isn't it the access modifier that helps in encapsulation? ...

Is dynamic_casting through inheritance hierarchy bad practice?

c++,oop,inheritance,casting
I have got the following data structure: class Element { std::string getType(); std::string getId(); virtual std::vector<Element*> getChildren(); } class A : public Element { void addA(const A *a); void addB(const B *b); void addC(const C *c); std::vector<Element*> getChildren(); } class B : public Element { void addB(const B *b); void...

(Java) What kind of argument is this? With a [duplicate]

java,oop
This question already has an answer here: What is the ellipsis (…) for in this method signature? 5 answers Please can anybody explain, I found this in a program on the Internet. I googled it up but nothing helped as I don't know what it is called? Why are...

Calling Protected Function From Derived Friend Function

c++,oop,friend,derived-class
I have a base class, Animal, and a derived class, Lion. Animal has a protected function called eat(). I would like to call eat() from a friend function defined in Lion, but when it won't compile: error: call to non-static member function without an object argument Why can't I call...

Class variables in OOP

python,oop
I am trying to develop a car-dealership-customer model to really understand OOP using Python. The problem I am running into is that I'd like to define Car as a separate class object from the Dealer class. This causes confusion; how can I use Car attributes and upload them into the...

Serial modification of objects in R

r,oop
I have a number of matrices of the same size: m1.m <- matrix(c(1,2,3,4), nrow=2, ncol=2) m2.m <- matrix(c(5,6,7,8), nrow=2, ncol=2) ... I want to set uniform column and row names to all of them. Currently I am doing it like this: new_col_names <- c("Col1","Col2") new_row_names <- c("Row1","Row2") change_names <- function(m,...

PHP mysqli_fetch_array() OOP style

php,oop,mysqli
I want to run a SELECT query and fetch data as associative array and echo the fetched data. In procedural style I would use mysqli_fetch_array(). But I am now trying OOP style. I have tried this code: $con= new mysqli('localhost','root','','afiliate'); $query="SELECT * FROM product WHERE ID=? "; $stmt->bind_param("i",$ID); /* $ID...

Creating attribute defaults by calling a wrapped object

perl,oop,moose
I have WrapperClass object that has an InnerClass object as an attribute. The InnerClass object has a weight attribute. My WrapperClass object also has a weight attribute and I want its default value to be whatever the value of the InnerClass object's weight attribute is. #!/usr/bin/perl package InnerClass; use Moose;...

PHP Data Objetcs (PDO) example

php,mysql,oop,pdo
I'm fairly new to object oriented programming in php, I just wrote the following script to create a connection using PDO and run a simple Select Query. It works fine, i just need to know if i have done it right! (need to know the best practices i'm missing). <?php...

missing 1 required positional argument: 'key'

python,oop,python-3.x
class Keys(): def __init__(self): self.key_list = {1:"one", 2:"two", 3:"three"} def get_name(self, key): self.ddd = key key1 = Keys key1.get_name(1) why after start this code I get error Traceback (most recent call last): File "class.py", line 8, in <module> key1.get_name(1) TypeError: get_name() missing 1 required positional argument: 'key' I usage python3...

How to avoid anemic data model? Can repositories be injected into entities?

java,oop,design,domain-driven-design
I have an immutable User entity: public class User { final LocalDate lastPasswordChangeDate; // final id, name, email, etc. } I need to add a method that will return information if the user's password must be changed i.d. it has not been changed for more than the passwordValidIntervalInDays system setting....

Find method contents from a method in superclass? (Java/Eclipse)

java,eclipse,sockets,oop
I want to find the contents of the java.net.ServerSocket accept() method (because I am trying to override it so it returns a different type). Is this possible in Eclipse, or for that matter, in Java? Thanks....

C# Code design / Seperate classes for each TabControl

c#,oop,architecture,software-design,code-design
My main problem is that my tool grows and grows and I start loosing the focus on the different parts of my code. The main-Form got a docked tabControl at fullsize. I got 5 different tabs with for really different functions. So I can say my tool is splitted into...

Avoiding type checking when interface method parameters are abstract

c#,oop,interface
My interface looks like this: public interface UserHandler { CheckUsernameResponse CheckUsername(CheckUsernameRequest request); } The request and response types in the signature are abstract classes, giving a usage of something like: var fooHandler = new FooUserHandler(); var fooResponse = fooHandler.CheckUsername( new FooRequest { id = 1, FooProperty = "abc" }); or...

Loop by Object inside another Object in Java

java,list,oop,collections
I'm not sure how to ask this in word so here's an example : Building class have a data like this : Map<Season, List<Info>> infosBySeason = new TreeMap<Season, List<Info>>(); What I'd like to do is loop for each Building, print by Season infos. Like : Season 1 : Building 1...

What is this thing called in Java?

java,oop,object,inheritance,immutability
Google isn't being very friendly today, and I'm researching some OOP techniques I've not used in the past. Basically, I've noticed some libraries have variables with preset choices, like new Website(Websites.STACKOVERFLOW). What is that called, when you've got apparently immutable values like that? What if I want to create my...

Actual class of object reference

java,oop,inheritance,polymorphism,instanceof
Given three classes A, B, and C, where B is a subclass of A, and C is a subclass of B. (a) (o instanceof B) && (!(o instanceof A)) (b) (o instanceof B) && (!(o instanceof C)) (c) !((o instanceof A) || (o instanceof B)) (d) (o instanceof B) (e)...

creating multiple objects with browserify

javascript,oop,browserify
I am trying to use the design pattern as below: human.js function Human(name){ this.name = name this.sayName = function(){ console.log(this.name); } } var a = new Human("bob"); var b = new Human("ted"); However I haven't used browserify much and I don't know how to do this in browserify. What I...

JavaScript Functional Classes [closed]

javascript,oop
I am learning object oriented programming in JavaScript from an Udacity course. I would like to know which among the below is the best technique to create an Functional Object and why. First code: var Car = function(loc){ var Obj = {loc:loc}; extend(Obj, Car.methods); return Obj; } Car.methods = {...

Laravel5: Access public variable in another class

php,class,oop,laravel,laravel-5
I have a middleware file called LanguageMiddleware.php: ... class LanguageMiddleware { //ISO language codes: public $languages = ['en','es','fr','de','pt','pl','zh','ja']; ... LanguageMiddleware.php is in laravelProj/app/Http/Middleware/ Here's my problem: I have a blade template file called master.blade.php where I'm attempting to output a list of languages @foreach (App\Http\Middleware\LanguageMiddleware\languages as $lang) <a class=\"setLang\" href=\"lang/en\">{{...

My simple php class not working [closed]

php,class,oop
I wrote a simple class. but its not working. Something is wrong. can't find error line class Host { public $scheme; public $hostname; public $www; function __construct(string $scheme,string $hostname,string $www) { $this->scheme = $scheme; $this->hostname = $hostname; $this->www = $www; } public function get_URL() { return $this->scheme.'://'.$this->www.$this->hostname; } } $site...

PHP extend existing class for table insertion/update

php,mysql,class,oop
I am curently working on a extended class and still have no ideea if this would be the best way to do it Let's say the primary class is something like the above (keep in mind the fields from table are more than 2, but for demo purpose I only...

Can i use only _ (underscore) for the name of the class?

php,oop
Can i use only _ (underscore) for the name of the class if yes then how object will be create and if no then why not? class _{ } ...

Python 2.7 @property usage results in error “global name '_c__pro' is not defined”

python,python-2.7,oop,properties,encapsulation
I wrote a simple class in Python2.7 that should use the @property functionality. class c(): def __init__(self): __pro = 1 @property def pro(self): return __pro *10 def setpro(self, x): __pro = x Now when I create an object from this class and try to access the pro property, I get...

Understanding difference in Swift properties for structs and classes in assignment

ios,swift,oop,struct
My question is in regards to an error that I kept on seeing while writing a function to initialize an optional array in a struct that I solved by just changing the struct to the class. I am hoping that someone can explain to me what I am not understanding...

Calling an object and its method from another object class method

javascript,class,oop,object,methods
I have created some classes/objects for some animations. I created a class called Navigation(), and another class called Stars(). Each of the classes have their own methods and objects associated with them. I have created a method within the Navigation() class that attempts to run a method and the object...

How to extract variable from one function into another in same class in php

php,oop,abstract-class
I want to use variable value from one function into another function of same class. I am using abstract class using which I am declaring variable as global indirectly. I can not declare variable as global in the class. My demo code is as follows: <?php abstract class abc {...

Call to a member function query() on a non-object in PHP when trying to access parent constructor in php

php,mysql,oop
I don't seem to be able to access the parent class constructor In PHP. Here is the code class Mysql { const SERVER, USER, PASSWORD, DB; function Mysql() { return mysqli_connect(self::SERVER, ETC); } } class Mysql_Select extends Mysql { function Mysql_Select() { $conn = new Mysql(); etc } } I'm...

AttributeError: Type Object 'Ned' has no Attribute 'attack'?

python,class,oop,super,attributeerror
Here's my code: Classes: class Player(object): """Base class for the player""" def __init__(self, name, armour, attack): self.name = name self.armour = armour self.attack = attack class Ned(Player): """The main player""" def __init__(self): super(Ned, name="Ned", armour=10, attack=3).__init__() Line Causing the Issue: entities.Ned.attack += 3 When I run this, I get: AttributeError:...

Add key and value (as argument via function) to array

php,oop,associative-array
First we have a property which is the array: private static $_errors = array(); An error can be added by sending it to a function, which will add it to the array: public function addError($error){ self::$_errors[] = $error; } In any function, I can easily add an error as a...

Why does the “this” keyword refer to the subclass too?

java,oop,this
In the following scenario, Main.registerEvents(Listener) is part of an event system of a game API. Let's say it should register any method with the @EventHandler annotation. public abstract class Spell implements Listener { protected Spell() { Main.getInstance().registerEvents(this); } @EventHandler public void onMove(PlayerMoveEvent event) { } } public class Fireball extends...

Why does Instagram's pagination return the same page over and over?

php,wordpress,oop,pagination,instagram
The Code I've created a PHP class to communicate with Instagram's API. I am using a private function called api_request (shown below) to communicate with Instagram's API: private function api_request( $request = null ) { if ( is_null( $request ) ) { $request = $this->request["httpRequest"]; } $body = wp_remote_retrieve_body( wp_remote_get(...

program that creates one main object and creates a pet for each of them [closed]

swift,oop
I am new to swift coding and I was wondering how you would create a program that creates one main object and creates a pet for each of them. Would you use a string, array or what?

Calling an add on a list from a getter of an object does not work as expected

java,oop
So I have an object with a list field and I am accessing the list using a getter. public class Customers{ private List<String> names; public Customers(List<String> names){ this.names = names; } public List<String> getNames(){ return names; } public String toString(){ StringBuilder sb = new StringBuilder(); for(String name: this.names){ sb.append("Customer:"); sb.append(name);...

Python class design: explicit keyword arguments vs. **kwargs vs. @property

python,class,oop
Is there a generally accepted best practice for creating a class whose instances will have many (non-defaultable) variables? For example, by explicit arguments: class Circle(object): def __init__(self,x,y,radius): self.x = x self.y = y self.radius = radius using **kwargs: class Circle(object): def __init__(self, **kwargs): if 'x' in kwargs: self.x = kwargs['x']...

Why is 1_2_3_4 a valid integer literal in java? [duplicate]

java,oop,inheritance,integer,literals
This question already has an answer here: Meaning of 0_0 in Java 7 [duplicate] 3 answers Wierd Syntax - Underscores between digits 1 answer Why does the following work? int a=1_2_3_4; System.out.println(a); // 1234 ...

Global function or function with no name java for factory pattern

java,oop,factory-pattern
I want to declare a factory class with some methods and attributes that can be used like this: ClassFactory myObj = MyObj("Class1").method1("input 2"); It seems that this is not a valid JAVA statement because JAVA is fully Object oriented and don't let to declare global function. But if there are...

How to get rid of duplicate code in derived classes?

c++,oop,inheritance,override
I have a class hierarchy like: class A { list<A*> children; public: void update() { do_something(); update_current(); for(auto child : children) children->update(); } protected: virtual void update_current() {}; }; class B : public A { protected: void update_current() override { do_something_important(); }; }; class C1 : public B { protected:...

Passing variable data between classes OO Javascript

javascript,oop
I am trying to create a basic app for creating and editing contact details - for the purposes of improving my JavaScript skills. For some reason I can't manage to pass variable data from one class to the next - I'm trying to implement something similar to an MVC just...

How to implement repeated behavior when inheritance isn't an option

java,oop,interface
I have two classes which share some properties and behavior. One such cluster of common behavior is manipulation in 3D space. As such, each implements interface Transformable: public interface Transformable { public void position (double x, double y, double z); public void position (Tuple3d tuple); public void rotateDeg (double yaw,...

Class fields as method parameters

oop,groovy
My method needs to be strictly typed. If possible, I wanted to save some line of codes, setting the model properties from the parameter input by putting the model properties setter directly at the function definition. The current working code: class Connector { static def entityQuery( String httpMethod, String typeName,...

Using $_GET in class

php,class,oop
Im learning PHP OOP little by little by myself... I can't get this to work the way I want, im triying to do this: http://localhost/test/class.php?action=delete public $action; public function __construct() { $this->action = isset($_GET['action']) ? $_GET['action'] : null; $this->db = new Db(); $this->Select($action); } private function Select($action) { if ($action...

What is the proper way to use inheritance when combined with factory method?

oop,design-patterns
Given that I have 3 classes Asset, AssetA, AssetB what is the proper way to structure inheritance when using the factory method? Here is how I would like to use these classes: Asset.new(data) should deterministically create either AssetA or AssetB depending on some flag present in data Asset should also...

Object Oriented Python - rectangle using classes and functions

python,function,class,oop,methods
I am creating a program in Python that will utilize object oriented programming to print the properties of a given rectangle. The project has these given constraints: The purpose of this lab is to give you practice creating your own object. You will be given a main function that expects...

Python 3.x error with methods asking for input error is TypeError: __init__() takes 0 positional arguments but 1 was given

python,oop,python-3.x,methods,user-input
I'm attempting utilizing TeamTreehouse learning subscription & this Starting Out With Programming Logic And Design (3rd Ed) book to attempt learning programming & Python. Please don't shoot to kill me I'm learning. Goal: I'm attempting to set a Pet class with 3 fields/attributes/properties. The class will have 2 methods, set...

Getting ArgumenError while trying to create instance of a ruby class

ruby,oop,encapsulation,argument-error
I am trying to improve my OO ruby skills. I've created a class and when calling and trying to make ans instance of it, I get error. Here is the code. class EncapsulatedPerson def initialize(name) set_name(name) end def name @first_name + " "+ @last_name end def set_name first_name, last_name =...

Is it bad practice to have a static class that does not instantiate objects

java,class,oop
I read that a class is like a blueprint for an object. So is it considered bad practice to declare a class but then in the program, never actually create instances of the class (but just have static methods in the class)?

Bound mismatch: The type is not a valid substitute for the bounded parameter

java,oop,generics
I've recently started implementing a few data structures and, well, I am trying to make everything as 'extensible' as possible. public abstract class AbstractNode<E extends Element, U extends AbstractNode<E, U>> { ... } public class BinarySearchTree<Element> extends Tree<Element, Node<Element>> { ... } public class Element implements Cloneable { ... }...

Where is the defination of rails validators?

oop,ruby-on-rails-4
I am a beginner in rails. As I was working on rails validation, I wanted to know where is the definition of valid? and new_record? and all the validation helpers? I was trying to find the definition of all these functions but couldn't find any. Where do all this validations...

calling a method to restart if a condition is met without using a loop

java,user-interface,oop,jtextfield,jtextarea
I am working on a payroll program for school. I only two weeks into working with GUIs so my skills have a lot of room for growth. Everything works fine except for this method. I am trying to get the method to clear the JTextAreas if the number entered is...

Fatal error: Using $this when not in object context in E:\xampp\htdocs\

php,oop
I am getting a Fatal Error while calling a public method using Scope Resolution Operator. Here is the part of the code: Class userrole { public function get_premium_subscritpion($userID) { $userID = ($userID == '') ? $this->user_info->ID : $userID; if (empty($userID)) return false; /* Check if user has subscribed */ if...

Javascript: Access function within deep object on parse

javascript,oop,object
I have an object var object1 = { object2: { function1: function(a, b, c, d, e) { //do some stuff with those parameters console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d); }, function2: object1.object2.function1(2, 3, 4, 5) }...

How to transform a method call pattern found in multiple methods into a simpler OO mechanism?

php,oop,magic-methods,facade
In my class I have a lot of functions that simply redirect code to a DAO class (a class that forms business objects from data from a database). Is there a way to maybe create a single function that replaces all of the functions below? public function getIdFromModel($model) { return...

Java Design Issue: Enforce method call sequence

java,oop,design-patterns
There is a question which was recently asked to me in an interview. Problem: There is a class meant to profile the execution time of the code. The class is like: Class StopWatch { long startTime; long stopTime; void start() {// set startTime} void stop() { // set stopTime} long...

“Undefined method PDO::execute()” despite using prepare

php,oop,pdo,undefined
This code has been working before, but I recently added a database class. I get the instance and connection from it: $connection = MYSQLDatabase::getInstance()->getConnection(); $connection->prepare("INSERT INTO users etc etc....... $insertArray = $connection->execute(array( ":username" => $_POST["username"] )); getInstance() returns the database instance. getConnection() returns the connection property which contains: new PDO('mysql:host='...

Why metaclass's __call__ method called on class, but native class's __call__ not?

python,oop,metaclass
class Meta(type): def __call__(cls, *args, **kwargs): print 'Meta.__call__ called.' return super(Meta, cls).__call__(*args, **kwargs) class MetaInstance(object): __metaclass__ = Meta # Instantiate class. MetaInstance() # Meta.__call__ called. class StandardClass(object): @classmethod def __call__(cls, *args, **kwargs): print 'StandardClass.__call__ called.' return super(StandardClass, cls).__call__(*args, **kwargs) # Instantiate class. StandardClass() # StandardClass.__call__ is not called! Why metaclass's...

Nested objects in Python

java,python,oop
I am realizing a porting from Java to Python. Now, I would like to define an object by using another one as neested attribute. To be clear, taking into account the Java code as follows: public class Foo { private String fooName; public Foo(String fooName) { setFooName(fooName); } public void...

Multidimensional array in class C++

c++,arrays,oop,multidimensional-array
I have an error when compiling my code, with multidimensional array. C:\Users\Tobi13\Desktop\Projet C++\Code\Test\Test111\map.hpp|17|error: declaration of 'levelchargement' as multidimensional array must have bounds for all dimensions except the first| And I don't understand at all. I have searched on the internet but I didn't found anything. The code of map.hpp class...

Why has java kept length field in the jvm public

java,oop
Here is an example: int[] a = {10}; int x = a.length; We read incessantly to hide variables and use accessors. Why was that rule violated here?...

How to get the name of child class from base class when an object of child class is created

php,oop
I want to get the name of my child class in the base class so that whenever an object of child class is created I get the name of the child class in my base class. Something like this: class Base_class { function __construct() { // Some code Here to...

JS: Is it possible “something(arg)” and “something.my_method(arg)” at same time

javascript,function,oop,methods
I know how create just a function something(arg) something = function(arg) { console.log('Function result', arg); } I know how create an object with function something.my_method(arg) something = { my_method: function(arg) { console.log('Method result', arg); } } Is it possible to write code, wher both something(arg) and something.my_method(arg) are exists? Like...

Python method that can be called on a list of objects

python,oop,syntax
When a method is called on an object in python as: obj.func() then python passes the obj as the first argument to the func(). I want to do something like: [obj1, obj2].func() and have it processed as: [obj1.func(), obj.func()] Is there a way of defining this kind of methods in...

TypeScript project organization, compile into a single JS file?

javascript,oop,typescript
Recently I started working with TypeScript, using WebStorm IDE. Coming from a strong AS3 background I found TS a really good way to write JS, most of the concepts feel really familiar and convenient, but, when it comes to splitting classes,modules into separate files things starting to get really confusing....

Moving all fields info from one object to another

java,oop,object,field
Can I somehow move all field values from one object to another without using reflection? So, what I want to do is something like this: public class BetterThing extends Thing implements IBetterObject { public BetterThing(Thing t) { super(); t.evolve(this); } } So, the evolve method would evolve one class to...

Downcasting doesn't work and functions called from object own class instead of where the function is (Java)

java,class,oop,methods,casting
i have this classes hierarchy: public class Musician { private String name; public String instrument; public Musician(String name, String instrument) { this.name = name; this.instrument = instrument; } public String getName() { return name; } public String getInstrument() { return instrument; } private String getClassName() { return "Musician"; } public...

PDO FETCH_CLASS multiple rows into array of objects

php,arrays,oop,pdo
I'm trying to fetch multiple rows of bookings from a database and I want each one to be an instance of a specific class - so I attempted to store them within a multidimensional array. So far it works in terms of creating the array of objects, however I need...

Interface for Child Class that Inherits from parent class without reimplementing parent class

c#,oop,inheritance,interface
Currently I have the following: public class ChildClass : ParentClass {... ParentClass implements an interface as follows (I need ParentClass to be instantiated and therefore can't be abstract): public class ParentClass : IParentClass {... I also want child class to implement an interface so that I can mock this class...

Nested pointer instead of inheritance

c++,oop,inheritance
I have some source code in C++, which I need to understand and extend / modify. According to the documentation some classes are planned as base and derived classes to implement an inheritance mechanism. When I look into source code, the derived class is not derived from the base class...

Javascript, Array of Objects?

javascript,oop,jquery-mobile,mobile
I am a bit of a JS noob, but have good .net experience in my pocket. I am working on a mobile website/app, and I have collected some data similar to business listings from a custom web service. On .net, I would have, at this time, started building a custom...

Solving a java riddle

java,class,oop,if-statement
I'm given class A and class C, and I'm supposed to write class B which makes the output of the main in class C always successful! . Sine there is a random boolean variable, I get a good result only when it's false, when it's true I don't get an...

Check if object has given properties

php,oop
Other than doing something like the below code, is there a better way to check if an object has several given properties? <?php class myClass { public $a=1; public $b=2; public $c=3; public function checkProperties($obj,$props) { $status=true; foreach($props as $prop) { if(!isset($obj->$prop)){$status=false;break;} } return $status; } } $myObj=new myClass(); print_r($myObj);...

What is the default value of internal [[prototype]] property in JavaScript?

javascript,oop
Every object has a [[prototype]] property. By default its an instance of global Object constructor. What confuses me is this code: var obj1 = {}; var obj2 = {}; console.log(obj1.__proto__ == obj2.__proto__); //true Here [[prototype]] of both objects reference the same instance of Object. My question is: does JavaScript have...

Is Django For A Suitable For A Procedure Orientad Programming Lover? [closed]

python,django,oop
I have lack of knowledge on Python advanced OOP. Even though I know basic OOP. How to create a class, role of self, craft objects, basic understanding of init and super function etc. I just wanted to know is it good enough to learn Django? Or Django is like PyQt....

Is bootstrap file a controller?

php,oop,model-view-controller,controller
Sometimes, there are things that should be done at the very beginning of execution. And, I called it 'bootstrap' or 'initialization'. In bootstrap file, I usually disable the magic quotes at the runtime, set up the database adapter,defining paths, registering the autoloader, etc. Is it right to put that bootstrap...

Python: I'm getting an error when using self.name

python,oop,self
I made 2 programs, one that works here: class dog: amount_of_dogs = 0 def __init__(self, name, playfulness): self.name = name self.playfulness = playfulness dog.amount_of_dogs += 1 dog1 = dog("Ruffer", 1000) dog2 = dog("Skipper", 400) dog3 = dog("El Diablo", 30000000) print "The dog names are:", dog1.name, ",", dog2.name, ",", dog3.name, "."...

Validation within Get/Set Methods Java

java,oop,boolean,encapsulation
I have the following code that verifies user input using get/set methods.Only strings are acceptable.The while loop should continue to execute till the time the user enters the correct data type.However,my while loop continues to execute despite identifying incorrect data types.Suggestions? public class SetGet { public static void main(String[]args) {...

Function pointer to singleton class instance function

c++,oop,pointers,singleton
What I'm trying to do is create a function pointer to a single class instance function. I want to do this so I can do something like this: C->member_method(); instead of: Config::inst()->member_method(); but I'm not sure how to go about it. Here is my singleton class: class Config { private:...

base class pointer, invoke method based on derived type

c++,oop,inheritance,polymorphism
I understand that the following code doesn't work -- can't convert base to foo. Is there something I can do, or some pattern to employ which would get me close the behavior I'm trying to achieve in the code below? IOW, if I have a base class pointer to a...

Why there isn't library of design patterns?

java,oop,design-patterns
I'm new to design pattern subject. If design pattern are so great, why can't someone build a library of them so I don't have to create them in each application?...

Extending a method in PHP

php,oop
I have two methods which are 90% identical, ie 90% repetitive code. I am trying to extend the 2nd method. First Method: public function getResultsByID($userID = null){ $sqlParams = array(); if (!$userID) { throw new Exception("No User ID Provided"); } $sqlParams['userID'] = $userID; $sql = "SELECT t.user_id, t.owner_id, t.store_id FROM...

How to check if objectB used instance of objectA from objectA using private variables

php,oop
Code Explanation I have two classes, mesh and geometry, that are used to maintain attributes of a 3D array to fill a space. First a mesh is defined and builds a 3D array. Then geometric shapes can be created within the same bounds of the mesh object, but not in...

Symfony : is it better to use a trait or an intermediary class to complete Controller one?

php,oop,symfony2
I know it exists bundles like FOSRestBundle to achieve that but it can be quite complicated to use it. So I decided to create a simple RestController class to add more "automatized" methods to list/add/update/delete entities. So my first question is : is it better to use a trait or...