3 votes

Doubt concept oriented to objects

I'm starting in the world of object-oriented programming, leo and leo's examples but don't understand the concept or the philosophy of this form of programming.

I come from the world of industrial programming (robotic, plc, industrial etc...) structured Programming and process oriented, which has its declarations of variables and I work with them from any point in the program with any of these variables, let's say that are shortcuts global...

Now comes the case of the POO... To start with, in C# directly I have to have a class, llamemosle X in which I'm creating procedures and in one of these instancio a class Y.

As I have ordered my program (or structured), I do other different classes to treat other parts of my program.

The problem I have normalente is the following:

I need to access properties or methods of the object that instancie of the class And into another class and zasca! I don't have permissions because this instantiated in another class... what the hell? I don't understand why... If I need to access that do I do? Pattern singleton... But always? I don't see the benefits of the POO...


no, I do not mean that... Let Me explain;

    namespace Espacio1
    {
        public partial class Principal : Form
        {
            public Principal()
            {
            int var1 = 100;
            }
        }
    }

    namespace Espacio2
    {
       public partial class CUALESMIIP : Form
        {
            public prueba()
            {
                *******************
            }

How do I access the value of var1 from the procedure test()?


I do not mean to create a property and call it, rather, the example is as follows;

    namespace ConsoleApp3
    {
         class Program
         {
             static void Main(string[] args)
            {

                Console.WriteLine(ConsoleApp3.Class1.variable);
            }
         }
    }

    namespace ConsoleApp3
   {
        class Class1
        {
            public int variable = 100;
        }
    }

What I need is to check the value of "variable", but that same value, it does not instantiate the class and use it in another with a different value... I Seek to read a specific value, that is to say, if I at a given time I don't need to use a class as such... (properties, methods etc... do I Need to create the code in a class as such? What here there is not a procedure as such? that is not within a class... :D

4voto

gbianchi Points 11849

I'm going to be clear, I'm not going to use complicated names or I'm going to indicate the tutorials, if not I'm going to explain your problem clearly.

A class is nothing more than a part of your program encapsulated.

As well as in procedural programming, you have functions, and armabas libraries of functions, a class is nothing but a library of functions with their own variables. Then what makes your program is to create small libraries, which have their functions and their variables themselves, many times.

What we see better with a small example.

Procedural:

I want a list of cars. Then we would have to have a vector with the patents.. and if I want the color? well, we would have a vector containing another vector within that has the data of the patent and the color... and if I want the tire pressure? would have a vector that contains a vector of cars that have patent, color, and a vector of the tire, in each position has the pressure.. phew... imagine if I also want to add the type of tire (because I have four different!)

Not to mention how to use this.. imagine to try to cross it...

Classes:

I want a list of cars. Then I have the class car. This class has a variable patent. a variable color. a vector tire with the pressure of each one. To use it, you create a vector that in each position has a car (an element of the class car). and you access directly to its properties (the variables that you created at the class level, which let's say are global to the class, they are called properties). Since we are in classes functions are called methods.

And if I want to add the type of tyre?? then you could have a class tyre, and that my class car, vector, tire has an instance (i.e., a small "library" self-contained methods and variables), for each tire. it is more.. imagine that if you wanted to add the color of the tire (yes, I have problems and I want my tires of various colors), objects reaches me with adding a property to the class tires with the color.. Now imaginatelo procedural...

Now, beyond these benefits, are forced to use classes?

Of course not. your program could be a single class that has everything inside. And that doesn't change anything. you could work in an environment that POO with a single class and handle it fully procedural.

By reviewing your example, your main problem is the SCOPE. The variables inside the methods are the same as the variables inside the functions procedurals. Die there. to view properties, you must create them at the class level, outside any procedure in the class, as if they were global.

And yes, you can use static classes (which don't need to be created before being used) and lots of tricks more. But since all that depends on which type of system you are working on.

Edited:

According to what you added to your question, and maybe I did not explain well, but you don't need another class to store the value of a variable. Can be in your same class where to look for it.

in your case, variable could be in the class program

namespace ConsoleApp3
    {
         class Program
         {

             public int variable = 100;

             static void Main(string[] args)
            {

                Console.WriteLine(ConsoleApp3.Class1.variable);
            }
         }
    }

And if you wanted the value of this inside a class? Well, there we have lots of ways to do this, but to simplify life, because you don't have that value at hand, in the class that needs it.

Believes that, in the example of the car, each time we create a self, this is created without data. In general, the classes do not have data of their own (they are created empty), and one has to complete them. (yes, you could have a class with lots of strings static; and it does; but this is only an idea for a beginning).

So that the values are in another class and you can access them without "creating" class, for example, classes are used that are called static. These are like "libraries" already loaded, which will always maintain the values that they contain, but you are not the instancies. Technically they are instanciadas already when you load the program in "somewhere" that we are not interested in, but that allows the use.

2voto

Sr1871 Points 3160

You do not have permissions? what do you mean exactly?

Unless you're declaring your variables as private, or in special cases protected, you have access to the methods and attributes through an object

I don't know C# but I will give a general example of POO-oriented, a bit of java

public class X {
   private int atributo1;
   public int atributo2;

   public void funcion1() {
   }
   private void funcion2() {
   }

}

If you create a new object of this class x = new X(); you'll get access to the attribute 2 given that it is public and the function 1, attributes 1 and functions 2 you do not have access from the given object that is private only within the class, in some languages there is also protected that allows you to enter, and when it is a child class, (inheritance), I recommend You look for a lot of encapsulation, as it is one of the key parts in my mind of POO

2voto

Pikoh Points 14282

I would like to give you a good answer, but the problem is I don't understand which is your problem. The example of your second issue is solved by turning your variable in static and in that way, you could access to variable the following way:

namespace ConsoleApp3
{
     class Program
     {
         static void Main(string[] args)
        {

            Console.WriteLine(Class1.variable);
        }
     }

     class Class1
     {
        public static int variable = 100;
     }
}

Anyway, it would be best to put some real-life example, so that we can advise you the best way to fix it. Now it is a bit abstract your doubt and I don't understand what the problem is you are trying to solve.

2voto

PaperBirdMaster Points 24910
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(ConsoleApp3.Class1.variable);
        }
    }
}

namespace ConsoleApp3
{
    class Class1
    {
        public int variable = 100;
    }
}

What I need is to check the value of "variable", but that same value, do not instantiate the class and use it in another with a different value.

You can't. The data variable type int belonging to class Class1 namespace ConsoleApp3 is an instance variable, so it does not exist without instance:

namespace ConsoleApp3
{
    class Class1
    {
        public int variable = 100;
    }
}

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            // varias instancias de Class1 
            ConsoleApp3.Class1 c1, c2;

            c2.variable *= 5;

            Console.WriteLine(c1.variable); // Muestra 100 
            Console.WriteLine(c2.variable); // Muestra 500 
        }
    }
}

What you're looking for is a class variable, in C# (and other languages alike) is achieved by using the qualifier, static:

namespace ConsoleApp3
{
    class Class1
    {
        static public int variable = 100;
     // ^^^^^^
    }
}

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            // varias instancias de Class1 
            ConsoleApp3.Class1 c1, c2;

            c2.variable *= 5; // Error! Es variable de clase, no de instancia

            Console.WriteLine(ConsoleApp3.Class1.variable); // Muestra 100 
        }
    }
}

-2voto

Ingwvanegas Points 146

Would be of this form

var1 would be a property, although there are more ways to do this.

namespace Espacio1
{
    public partial class Principal : Form
    {

        public int var1 {get; set;}

        public Principal()
        {

        }
    }
}

namespace Espacio2
{
   public partial class CUALESMIIP : Form
    {
        Principal _principal = new Principal ()
        public prueba()
        {
            _principal .var1 = 0;
        }
    }

Edited

I understand more thoroughly your question, in your place I would use the singleton pattern, in frameworks such as the two is implemented using a variable static something

public static int var 1;

you can call it from another class as your what expusiste however, there are best practices to make singleton with framework recent to avoid deadlocks you could do it the following way:

public class Class1
{
    // Variable estática para la instancia, se necesita utilizar una función lambda ya que el constructor es privado
    private static readonly Lazy<Class1> instance = new Lazy<Class1>(() => new Class1());
    // Constructor privado para evitar la instanciación directa
    private Class1()
    {
    }

    public int var1; 
    // Propiedad para acceder a la instancia
    public static Class1 Instance
    {
        get
        {
            return instance.Value;
        }
    }
}
// Clase de prueba
public class Test
{
   private static void Main(string[] args)
   {     
        Console.WriteLine(Class1.Instance.var1);    
   }
}

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X