java:initializing_classes_and_constructors
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionLast revisionBoth sides next revision | ||
java:constructor_basics [2020/09/12 04:58] – [Default constructors] mithat | java:initializing_classes_and_constructors [2020/09/16 17:58] – [equals(other)] mithat | ||
---|---|---|---|
Line 42: | Line 42: | ||
</ | </ | ||
- | upon instantiation, | + | upon instantiation, |
+ | |||
+ | One way to do this is to set initial values in the variable | ||
<code java> | <code java> | ||
Line 55: | Line 57: | ||
</ | </ | ||
- | With the above modification, | + | With the above modification, |
This approach works fine if your class is fairly simple. | This approach works fine if your class is fairly simple. | ||
Line 61: | Line 63: | ||
===== Default constructors ===== | ===== Default constructors ===== | ||
- | Another way to initialize a class is by using a **constructor**: | + | Another way to initialize a class is by using a **constructor**: |
- | A constructor that does does this looks like: | + | For example, after initializing the state of your object, you might want to output that your object was successfully created. |
<code java> | <code java> | ||
Line 142: | Line 144: | ||
</ | </ | ||
- | Writing a '' | + | Writing a '' |
+ | |||
+ | |||
+ | ===== equals(other) ===== | ||
+ | |||
+ | Another method that you can define and is a good habit to get into defining is '' | ||
+ | |||
+ | <code java> | ||
+ | public boolean equals(ClickerCounter other) { | ||
+ | return (this.count == other.getCount() && | ||
+ | this.maxCount == other.getMaxCount()); | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | It's up to you to decide what " | ||
+ | |||
+ | <code java> | ||
+ | if (myCounter.equals(yourCounter) { | ||
+ | System.out.println(" | ||
+ | } else { | ||
+ | System.out.println(" | ||
+ | } | ||
+ | </ | ||
Copyright © 2020 Mithat Konar. All rights reserved. | Copyright © 2020 Mithat Konar. All rights reserved. |
java/initializing_classes_and_constructors.txt · Last modified: 2020/09/16 18:15 by mithat