Difference between object and variable within class of class type

0

I have the following class:

Public Class Book
    Public isbn as Integer

    Sub New(isbn as Integer)
        Me.isbn = isbn
    End Sub
End Class

All right, if I want to create an instance variable I have to pass parameters to the constructor and everything normal, but what is the difference between an instance variable:

Public NuevoLibro as New Book(isbn)

And have a variable of type class inside the class (in this case I have created a variable called book):

Public Class Book
    Public isbn as Integer
    Public libro as Book

    Sub New(isbn as Integer)
        Me.isbn = isbn
    End Sub
End Class

This example is in visual basic, but in java it can also be done, so I guess this even has a name.

    
asked by Mauricio Rodríguez 31.10.2017 в 20:12
source

2 answers

0

Actually the sentence that is inside the Book class is the declaration of an instance variable, but not initialized:

Public libro as Book

That is, the book contains nothing.

Public NuevoLibro as New Book(isbn)

Here you have declared an object ( NewBook ) of type Book and have started it by passing the value isbn

    
answered by 31.10.2017 в 20:41
0

I think I understand your question.

In the object-oriented programming paradigm, classes have relationships with each other. When you have an object of a class that is part of the attributes of a second class we talk about a relationship called "has a" (or Aggregation to be more technical). For example:

public class Libro  {
   private Autor autor; // la variable autor es un objeto de tipo Autor
   private int numeroCopias;
   private String nombre;

   public Libro() {
       this.autor = new Autor();
       // constructor, casi siempre acà inicializarias el/los atributos de tipo clase
   }

   // mas metodos...
}

For the previous code snippet, it says that a Book "has an" Author. The variable author of type Author is just an uninitialized object, needed by the Book class to perform its processes (maybe there are methods in Author that are necessary for the Book class to work correctly).

When you do

Libro milibro = new Libro();

Then you instantiate the millibro object (which I think you already knew). Finally I recommend you read this article in Spanish: link . Greetings and I hope I have clarified your doubt.

    
answered by 01.11.2017 в 16:45