Im Confused about java objects. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Im Confused about java objects.

how can i tell the diffrence between a object, variable and instances do these have certain places? are instances only used in a class outside main?? example... class fish String goldfish; <<<<instance of class is goldfish also a object?? Int bubbles <<<<< instance of class is bubbles also a object?? are variables only used inside main class?? example String z; <<<< variable is z also a object?? int i; <<<<<<<<variable is i also a object?? sorry im self learning and sololearn is very clear.

29th Jul 2017, 5:50 PM
D_Stark
D_Stark - avatar
2 Answers
+ 2
This is an excellent question if you're just getting started in Object-Oriented Programming! A class is like a blue print for objects; it defines attributes (variables) and behaviors (methods). Class Fish describes fish. An instance is an instance of an object. It can have it's own values for the attributes (variables). It is one particular fish. A variable can exist inside a class or instance, but doesn't have to. For instance, you can use variables inside methods or in a for loop. related to your examples: class fish // yes, a class (note: it's common to name classes with a capital, so Fish) String goldfish; <<<<instance of class is goldfish also a object?? // Technically: yes, String is an object. However, in this case you probably // mean to declare a fish of type goldfish? (see below) // To create an instance of fish, use: Fish fish = new Fish(); // Here, fish is the variable pointing to the instance of Fish created. int bubbles <<<<< instance of class is bubbles also a object?? // this is just a primitive variable are variables only used inside main class?? // no, they can be used in any class or method. example String z; <<<< variable is z also a object?? int i; <<<<<<<<variable is i also a object?? // Again, String is technically an object, but here they are likely just variables. A small example of how you could use class, instance and variables: class Fish{ // class String name; // variable int size; // variable } class Goldfish extends Fish{ // subclass; inherits all variables & methods of class Fish public Goldfish(int size){ // constructor this.size = size; // setting variable size of goldfish to given size } } class FishTank{ Fish goldfish = new Goldfish(10); // instantiation of a new Fish of type Goldfish with size 10 } Using a variable without instance: for (int i = 0; i < 5; i++){ // int i is a variable // do something } Hope this helps! Let me know if you have additional questions.
30th Jul 2017, 1:15 PM
marit vandijk
0
love it thanks
30th Jul 2017, 1:34 PM
D_Stark
D_Stark - avatar