A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.
"Now it's high time that I tell you about constructors. This is really simple concept. Programmers have invented a shorthand way to create and initialize objects."
Without a constructor |
With a constructor |
MyFile file = new MyFile();
file.initialize("c:\data\a.txt");
String text = file.readText(); |
MyFile file = new MyFile("c:\data\a.txt");
String text = file.readText(); |
MyFile file = new MyFile();
file.initialize("c:\data\", "a.txt");
String text = file.readText(); |
MyFile file = new MyFile("c:\data\", "a.txt");
String text = file.readText(); |
MyFile file = new MyFile();
file.initialize("c:\data\a.txt");
MyFile file2 = new MyFile();
file2.initialize( MyFile file, "a.txt");
String text = file2.readText(); |
MyFile file = new MyFile("c:\data\a.txt");
MyFile file2 = new MyFile(file, "a.txt");
String text = file2.readText(); |
"I just finished learning about the initialize method…"
"Look harder. With constructors, the code is more convenient and compact."
"So it is. Here's a question. I know how to write an initialize method inside a class, but how do I write a constructor?"
"First, look at this example:"
Without a constructor |
With a constructor |
class MyFile
{
private String filename = null;
public void initialize(String name)
{
this.filename = name;
}
public void initialize(String folder, String name)
{
this.filename = folder + name;
}
public void initialize(MyFile file, String name)
{
this.filename = file.getFolder() + name;
}
…
} |
class MyFile
{
private String filename = null;
public MyFile(String name)
{
this.filename = name;
}
public MyFile(String folder, String name)
{
this.filename = folder + name;
}
public MyFile(MyFile file, String name)
{
this.filename = file.getFolder() + name;
}
…
} |
"It's easy to declare a constructor inside a class. A constructor is similar to the initialize method, with just two differences:
1. The name of a constructor is the same as the class name (instead of initialize).
2. A constructor has no type (no type is indicated)."
"OK, so it's like initialize, but with a few differences. I think I get it."
GO TO FULL VERSION