I wanted to study constructors, so I googled (googled: "search on Google", even if it's not Google) and pulled the code.
ctest7.java
class ctest7{
public static void main(String args[]){
Television tv1 = new Television();
tv1.dispChannel();
}
}
class Television{
private int channelNo;
private String housouKyoku;
public void setChannel(int newChannelNo){
channelNo = newChannelNo;
if (channelNo == 1){
housouKyoku = "FujiTV";
}else if (channelNo == 3){
housouKyoku = "NHK";
}
}
public void dispChannel(){
System.out.println("The current channel is" + housouKyoku + "is");
}
}
When I compile and run this, "Current channel is null" Is displayed. housouKyoku is not stored and is null.
It seems that if you fix this, you will get the following code.
java.ctest8.java
class ctest8{
public static void main(String args[]){
Television tv1 = new Television();
tv1.dispChannel();
}
}
class Television{
private int channelNo;
private String housouKyoku;
Television(){
channelNo = 1;
housouKyoku = "FujiTV";
}
public void setChannel(int newChannelNo){
channelNo = newChannelNo;
if (channelNo == 1){
housouKyoku = "FujiTV";
}else if (channelNo == 3){
housouKyoku = "NHK";
}
}
public void dispChannel(){
System.out.println("The current channel is" + housouKyoku + "is");
}
}
In the original ctest7.java code
Television(){
channelNo = 1;
housouKyoku = "FujiTV";
}
Is added.
Well, that's what initialization is. There is a theory, but if there is no content as the initial value, the operation will not work. That's why you need to set the initial value. You could write it directly in the method and overwrite it each time you call it, but that's not suitable for sharing large amounts of code.
Hmm.
[reference] "What is a constructor-Constructor-Introduction to Java-Let's programming" https://www.javadrive.jp/start/constructor/index1.html
Recommended Posts