-3

I understand that in the fields of a class, you can make the field type the name of another class and then in the constructor initialise that field by calling a new class of that type, i.e.

public class Auction {
    private Bid bid;
}
public Auction {
    bid = new Bid();
}

The main reason for doing this is, as I understand it, to access the methods of that class.

My question is I've noticed in some methods that there are local variables created that have a type of a different class with a variable name. What is the purpose of assigning a local variable name with a type of another class? Is this another way of just accessing those methods directly, even if it hasn't been done in the fields or constructor?

Filipp Voronov
  • 4,077
  • 5
  • 25
  • 32
Jimmyu
  • 21
  • 3
  • What you ask is unclear, can you elaborate (with some pseudo code) on "what is the purpose of assigning a local variable name with a type of another class?" –  Oct 08 '16 at 08:14
  • 1
    This has nothing to do with generics, you're setting a field to have a value which is the type of *another* class. Java `String` is a common class (I presume) you're used to using as fields. It's like that. – Elliott Frisch Oct 08 '16 at 08:15
  • Your code is invalid and I'm not 100% sure whether you're asking *"How to invoke instance methods without a instance?"* here. – fabian Oct 08 '16 at 08:16
  • Where in your question are there local variables? – OneCricketeer Oct 08 '16 at 08:19
  • so say in this method //close a bid public void close { Person p; Bid bid; for{Lots lot: lot} {.......The fact that both local variables p and bid have been given types that are of class Person and class bid, why is that? – Jimmyu Oct 08 '16 at 08:35

2 Answers2

0

You can do this assignment only if type of the right part is-a type of the left part. So, for example, you can use methods of left part' type with realization from right part' type.

Number number = new Integer(10);

See also OOP in Java and Polymorphism in Java.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Filipp Voronov
  • 4,077
  • 5
  • 25
  • 32
  • Please use `Integer.valueOf()`, see http://stackoverflow.com/questions/9030817/differences-between-new-integer123-integer-valueof123-and-just-123 –  Oct 08 '16 at 08:21
0

First of all, you need to learn some basics about OOP. We use Objects to model the problems and solve them in Object Oriented Programming.

These "type of a different class with a variable name" is an instance of a class, which is called an Object. We can assign a variable name to an object in order to use that object and its behaviors.

ThisaruG
  • 3,222
  • 7
  • 38
  • 60