I understand nothing about instances and constructors

Hello Everyone! :smiley:

I am pretty new to Java, but have some experience in Python 3. I really want to code Minecraft Plugins but first I have to learn Java (Because you have to code your plugins in Java). I have had no issues with the Java course, because a lot of stuff from Python carries over to Java. But the moment I started “Java: Introduction to Classes” I fel into a lot of problems. I know what classes are, but what are constructors, instances, instance fields? I think this is really important if you want to code plugins because you have to use the Spigot API for 99,9% of your plugin. Could I get an (easy) explanation of this?

PS: Sorry if my Engilsh is really bad, I don’t speak English natively

Thank you so much! :grin:

  • Casper

Link to the course: https://www.codecademy.com/courses/learn-java/lessons/java-introduction-to-classes/exercises/classes-constructors

Loosely, the java constructor is equivalent to the __init__ dunder method in a Python class.

>>> class Table:
...     def __init__(self, name):
...             self.name = name
... 
>>> wood = Table("wood")
>>> wood
<__main__.Table object at 0x7fb91db0d2d0>
>>> wood.name
'wood'

In java something similar might look like:

class Table {
	String name;
	public Table(String tableName){
 	  name = tableName;
  	}

  	public static void main(String[] args){ 	
  		Table woodTable = new Table("wood");
  		System.out.println(woodTable.name);	
  	}
}
//output: wood
2 Likes

Thank you for you reply. So is a constructor in Java the same as a function in Python? I think I understand it a bit. Do you maybe know what an instance is. Is it just a fancy way of saying “object” in Java?

Thank you! :smiley:

  • Casper

Hi @casperjanssen5568103, the dunder method __init__ isn’t really a traditional function so it’s deceptive to label it thus (yes, it’s a function within a class, but the point is that it does something very specific).

Object-oriented programming is a big paradigm in general, so the best I can do is point you to some resources like Object-Oriented Programming (OOP) in Python 3 – Real Python. Just note that Java leans object-oriented from the get-go so if you want to learn Java it’s good to get an idea of what Oop is all about.