I am having some trouble understanding classes in Java.
Such as how do you declare "Inputter" in the helper class like this?
public class Helper
{
public void Helper(String z)
{
if(z.length() == 0)
{
System.out.println("You can't leave it blank!");
System.exit(1);
System.out.println("It's not working... ;(");
}
}
public void Inputter(int a)
{
// blah blah
}
}
Would you call it like this?
Helper x = new Inputter();
Please help, and NO this is NOT a homework question.
Thanks,
Smiling
EDIT: Would this be right:
public class Helper
{
public Helper(String z)
{
if(z.length() == 0)
{
System.out.println("You can't leave it blank!");
System.exit(1);
System.out.println("It's not working... ;(");
}
}
public void Inputter(int a)
{
// blah blah
}
}
and declared with:
Helper x = Helper();
And thanks everyone for giving me a warm welcome to StackOverflow! :D
Your problem is not with classes, it is with constructors and methods, and the difference between them.
Methods can have any name you like, they must declare a return type (possibly void), and they're called like this:
ReturnType r = methodName(param1, param2)
Constructors are used to create instances of classes (objects). They must have the same name as the class, they must not have a return type (not even void), and they're called like this:
MyClass m = new MyClass(param1, param2);
There are several problems in your code:
Helper has the correct name for a constructor, but because it declares a void return type, the compiler will treat it as a method.
Inputter doesn't even have the correct name for a constructor. To use it as a constructor with new, it would have to be part of a class called Inputter
Perhaps you should start out reading the introduction to OO part of the Java tutorial.
Inputter() that you have defined is a method or you can call it a behavior. You cannot create an instance for a behavior.
One more problem is that you cannot have return types on a constructor. Helper is the class name and the constructor is having a return type which is incorrect
Regarding your quesiton, if you want to call Inputter, you should do it something like the following.
Helper helper = new Helper("test");
helper.Inputter(100);
It is a good practice to start methods with smaller case letters.
The only object here is Helper. If you want to make a new helper, then you will instantiate it by saying
Helper X = new Helper("blah blah");
If you want to call Inputter then you just say
X.Inputter(1234);
Which will call the Inputter function for the specific instance X of Helper
You must create an instance of Helper Before you can use Inputter:
Helper x = new Helper("some string");
to use Inputter, try this:
//create a new helper
Helper x = new Helper("some string");
//use the Inputter method of the helper.
x.Inputter(1);
The thing to understand here is that Helper is the class, x is an instance of a class, and Inputter is a instance method (which is different from a static method) in the Helper class.
Inputter in your code is not a class. It is a method.
To make following statement correct:
Helper x = new Inputter();
you would need to create Inputter class that extends Helper class.
Inputter is not a class. It's a method of the Helper class. So you cannot instantiate it.
You can call it like this
String someString = "some string";
Helper x = new Helper(someString);
int someInt = 1;
x.Inputter(someInt);
The new keyword is reserved for instantiating (fancy word for saying "making new") classes. The way your class is made, when you make a new Helper, a function is run. That is the construct function, and is named like the class.
Once you instantiate a class, you gain access to the goodies within it (exception is a static method/attribute, where anyone can access it); all within the class that isn't private or protected.
Now, a short intro on OOP (Object Oriented Programming):
You have classes, which are basically blocks of functionality. Within these classes are two things: Methods and Attributes (many names for that, but that's what I call them.)
A Method is basically a good ol` function: It has an input and an output.
An attribute is really like any other variable.
Now, in Java and many other OO languages, there's a separation between the class declaration and class instances. A class declaration is basically the static coded class; exactly what you put in the code. A class instance is taking the class declaration and putting it into use: You can change and use the methods and attributes inside them.
So, if you want to call Inputter, you should do it like this:
Helper bob = new Helper('Bloop');
bob.Inputter(42);
What happened here? We made a new variable called bob which has a type of Helper. When constructing the new Helper, we also run the constructor. Looking at the constructor function, we pass a value to it (in this case, 'Bloop'), and the function is run normally, without us having to manually call it.
Now we want to use the Helper class' Inputter method. For that, we need to access an instance of the Helper class (in our case bob), by using bob. (notice the dot), and then calling it like any other function: Inputter(parameters). Gluing it together we get bob.Inputter(parameters)
This was a really rather lame explanation of Object orientation that didn't cover that much, but it should get you started. I recommend getting a book about Java or reading online tutorials.
First, start with the basics.
Classes best represent nouns. That means a Class is a model of (typically) a thing. Methods best represent verbs on those nouns. Drifting away from this ideal is sometimes necessary; however, the further you stay away from such an ideal, the harder it will be to understand what is going on. With a nod to the exceptions, since you're a beginner let us not get wrapped up in the exception but follow the rule.
public class Person {
private String name;
private int age;
public Person(String name) {
this.name = name;
this.age = -1;
}
public void setAge(int value) {
if (value < 0) {
throw new IllegalArgumentException("Age must be greater than zero");
}
this.age = value;
}
public int getAge() throws IllegalStateException {
if (age < 0) {
throw new IllegalStateException("Age was not set");
}
return this.age;
}
}
Read through the class above, and use its style for your beginning programs. When you find that its style is hindering you more than helping you, then you might have found a place where other techniques are needed.
Related
In Factory method pattern there are 2 lead implementation (correct me if I'm wrong):
When Creator class is being abstract and not providing an implementation for the Factory method:
public abstract class CasinoGameCreator {
public void playGame() {
ICasinoGameType gameType = createGame();
gameType.play();
}
public abstract ICasinoGameType createGame();
Or, we can have the Creator class be a concrete class that provides implementation for the Factory method:
public class CasinoGame {
public static CasinoGame createGame(GameType type) {
if (type == GameType.BlackJack) {
return new BlackJackGame();
} else if (type == GameType.Poker) {
return new PokerGame();
} else {
return null;
}
}
}
Is there any strong preference when to use each implementation? if there is, in what general situations we whould prefer using the 1st approach over the 2nd?
Option 1 is following the Open/closed principle. This means: it is open for extensions (as different subclasses can implement different ways of creating a game); but it is closed for modification - the behavior of playGame() is fixed. Well, it is not; but if you use this pattern, you really would want to make playGame() to be final. If you have such an abstract class with an implementation X; and an abstract method Y (used within the other method X); than it doesn't much sense to allow subclasses to change X.
Option 2 is helpful when you are really sure about the different type of games; meaning: chances that this enum will ever change are small. Given the idea of games in casino; I very much doubt that this would be true here. Probably you could add a new game every other day. And then, you have to turn to each place that switches over the GameType and adapt that code.
So, given those thoughts, option 1 would be the first choice - because you can simply add a new game type by creating a new subclass of your creator class. This means: you can add a new game without touching the code responsible for other games.
Of course: if you would pick a different example, the requirements might be different, and then option 2 might have certain benefits.
Sometimes we call className.methodName() without creating object for it, I mean without using syntax as className objectName = new constructor() and then call as object.methodName()
When to use className.methodName()?
When to call method using object as object.methodName()?
Explanation of above two cases with example will be appreciated.
What you're referring to is a static method.
Assume that I have this :
public class A {
public static void foo(){
System.out.println("Hooray! I work!");
}
}
You can now do this anywhere else in any other class :
A.foo();
This is because the method is static, which means that it can be called on by the CLASS.
This means that it doesn't require an instance of that class in order for the method to be called.
However, even though it isn't required, you can still do this :
A a = new A();
a.foo();
But since the method foo() is static, instantiating an object A is not required in order to run the foo() method.
First. When you're create at least one static method of a class, you can use this method without creating an instance of class. This is useful, for example, for the creation of methods with independent logic. For example:
public class Checker {
public static Boolean month(int value) {
return (value >= 1 && value <= 12);
}
}
You need check correct value of month many times. But what to do each time to create the object. It is much effective to use a static method.
Second. When you create the object, the object is stored in the memory and you get a link to it. Then the object can be used for example to save at the list.
Method at this object is specific. You can save class data and do specific operation with member of this class. For example:
List<Animals> animalsList = new ArrayList<>();
Animal animal = new Animal("dog");
int legs = animal.getCountLegs(); // specific function for object
animalList.add(animal); //save if you need
// use list of object
For every class, we have a Object called as class object which is YourClass.class object. static methods are invoked based on meta-data on those objects. For instances of a class, methods are invoked on the actual instances. Both static and non-static methods are present on method area.
There is no different between 1 and 2 point, because in during compilation compiler makes ClassName.staticMethod() instead of instance.staticMethod().
Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.
I have noticed a thing that a constructor and a simple method of a class do the same work. what is the exact reason to create a construct of a class? If i create MyClass(){} constructor and MyClassMethod(){} method it will do the same work as I write the body part of those method and constructor. So what is the need of construct? Does it have any special use ?
A constructor and a method are two different things. The fact that you can write the same or similar code inside them is irrelevant.
When a new object is created a constructor is called. If you don't specify one the compiler will create a default one for you. This is the place where initializaton of the object's fields takes place and memory is allocated for the object. This is a concept that all object-oriented languages have. A new object must be initialized somehow. Memory needs to be allocated. In Java you don't manage the memory yourself (at least not directly anyway) so this is the purpose of the constructor. Note that since a constructor is always executed, this behaviour is enforced as soon as you call e.g. Person p = new Person();.
Now since a constructor is always being called, you have an option here: do you let the default constructor execute or do you create one yourself? Perhaps there are fields that need to be initialized in a way other than their default values. Or perhaps you need to not allow creating an object without providing some values. If you define a constructor yourself, the compiler does not create a default one for you. So if I have public Person(String firstName, String lastName) {} then I have created a specific rule that is again enforced by the system: a new object of class Person cannot be created unless you give a first name and last name:
Person p = new Person(); // this would give a compile error
Person p = new Person("John", "Smith"); // this is the only way to create an object now
Using a method you cannot enforce this. The programmer using your class might call your method or not. The constructor is a part of the lifecycle of the object. Methods define the behaviour of the object
Some points :
1) Constructors are the only way to set final instance variables .
public class SomeType {
final int x ;
SomeType(int y){
x=y;
}
}
2) A class with private constructor cannot be sub classed.
3) If your class is a subclass and the base class doesn't have a default constructor , then you need a constructor in your class to call the super class constructor.
One of the benefits of using a constructor over a method is that you can be assured the constructor was called and the work within the constructor was performed.
The language specifies that to construct an object a constructor must be called. So if you use a custom method to establish the initial state of your object, you will need to call the default constructor first. Why make two method calls when you can perform the work in one call the constructor and be assured the object has been properly initialized?
public class Test(){
private Integer x;
public Test(){
}
public Test(Integer x){
this.x = x;
}
public void setX(Integer x){
this.x = x;
}
public void doSomethingWithX(){
this.x.toString();
}
}
Test test = new Test(8);
test.doSomethingWithX(); //I know x has been declared and assigned
Test test = new Test();
test.doSomethingWithX(); //X has not been assigned results in NPE
If you create a new Object of MyClass it will automatically call the constructor - you can initialize all members within it, and be sure that this object´s members are all initialized.
Generally:
A constructor is always called once when you create a new Object of this class, and you can´t call it manually.
And don´t do "real" work in a constructor, as it will slow down the creation of objects of this class - only initialize your class/members there.
You can also use different constructors, depending on your needs - but if you create a constructor, there is no more default constructor!
Example:
public MyClass {
int score;
public MyClass(int sc) { // already know the score
score = sc;
}
public MyClass() { // don´t know the score yet
score = 1;
}
public void addScore() {
score += 5; // i know for sure that score is not zero
}
}
Essentially a constructor is just a special method that implicitly returns an object of its containing type. You should generally use constructors for creating objects - this is what people expect to see.
However, there is a useful idiom called the factory method (more info at this link) which is essentially using a static method to construct an object, the key advantages being
You can give a factory method a more descriptive name (whereas of course a standard constructor has to be named after the containing class).
They don't have to return an object, giving more flexibility.
They can return a sub-types of the class.
You can set final fields without initializer in a constructor. This helps to build immutable instances:
class Number extends Expr {
private final int n;
public Number(int n) {
this.n = n;
}
public int getValue() {
return this.n;
}
}
So after a constructor like this, you can rely on the fact that the instance is initialized completely (and in this case, it's values are immutable/constant).
Constructor is not like simple methods. It is called every time when the object of that particular class is created. You don't need to call it explicitly.
There are somethings that we need to do immediately when the object is created, for instance when you create a GUI kind of thing you want to set many properties on the time of creation like size of window etc.
Another benefit of constructor is security of class. You cannot create a object unless you know the right perimeters of constructor.
More details:http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type.
Some points :
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
These are the benefits of constructors.
Automatic initialization of objects at the time of their declaration.
Multiple ways to initialize objects according to the number of
arguments passes while declaration.
The objects of child class can be initialised by the constructors of base class.
I would have a string that is parsed into an array, as shown here:
class Example extends ParentClass {
private String[] array;
public static Example parseString(String lineToParse) {
array = lineToParse.split("\");
}
public ObjectType1() { // arguments: String, String, String
}
public ObjectType2() { // arguments: String, String, String, double, double
}
}
What I'm wondering is could I do this?
if (array[0].equals("Test")) {
public ObjectType1()
}
Or is there a better way to do this?
I want to create various objects with different arguments each, and the first argument (array[0]) will be applicable to each object, so I was wondering if I could create objects within an if statement like this, or a switch (not sure if that would work either).
I believe a factory method would be useful for you, one that returns instances of classes according to the parameter received:
// ObjectType1, ObjectType2, ObjectType3 inherit from ObjectType
static ObjectType getInstance(String[] array) {
if (array[0].equals("Test"))
return new ObjectType1(array);
else if (array[0].equals("Test2"))
return new ObjectType2(array);
else
return new ObjectType3(array);
}
For the record, actually you can define a class inside a method, this is valid code in Java ... of course, that's hardly a good thing to do:
// ObjectType1, ObjectType2 inherit from ObjectType
public ObjectType example(String[] array) {
if (array[0].equals("Test")) {
class ObjectType1 {
ObjectType1(String[] array) {
}
}
return new ObjectType1(array);
}
else {
class ObjectType2 {
ObjectType2(String[] array) {
}
}
return new ObjectType2(array);
}
}
"Creating" an object means "instantiating it", with new:
ObjectType1 foo = new ObjectType1(...);
You can do that anywhere it's legal to instantiate a class, including in an if statement.
You cannot define classes in arbitrary locations, however.
If you just want to call a method (which should start with a lower-case letter if you want Java developers to understand what you're trying to do), you can call it from anywhere, including inside if statements.
This sounds like you may want to use a [static factory method][1].
[1]: http://en.m.wikipedia.org/wiki/Factory_method_pattern
I guess that you want to dynamically create objects based on a configuration file?
There are lots of ways to achieve this. One simple way is to use reflection to create the objects. Then you do not need any if/switch statements, and if you want to create a new type of object your code does not need to be changed.
Here are some examples for using reflection: Reflection API Code Samples
class Creature {
private int yearOfBirth=10;
public void setYearOfBirth(int year) {
yearOfBirth = year;
}
void setYearOfBirth(Creature other) {
yearOfBirth = other.yearOfBirth; // is this correct it compiles fine
}
int getYearOfBirth() {
return yearOfBirth;
}
public static void main(String args[])
{
Creature c = new Creature();
c.setYearOfBirth(89);
Creature d = new Creature();
c.setYearOfBirth(d);
System.out.println(c.yearOfBirth);
}
}
Is there any mistake in this code?
Is "other.yearOfBirth" wrong? My faculty says it is wrong but it works fine for me.
As written, it will work, as you discovered. I suspect that there's a fundamental misunderstanding at play, though.
My psychic powers tell me that your instructor expected code more like the following:
class Creature {
private int yearOfBirth=10;
public void setYearOfBirth(int year) {
yearOfBirth = year;
}
public void setYearOfBirth(Creature other) {
yearOfBirth = other.yearOfBirth;
}
public int getYearOfBirth() {
return yearOfBirth;
}
}
class Program {
public static void main(String args[]) {
Creature c = new Creature();
c.setYearOfBirth(89);
Creature d = new Creature();
c.setYearOfBirth(d);
System.out.println(c.yearOfBirth); // This will not compile
}
}
The misunderstanding is that you've only created one class-- your main application class. This effectively makes yearOfBirth a sort of hybrid global value that you can access from your main method. In more typical designs, Creature is a class that is completely independent of your main method. In that case, you must only access Creature through its public interface. You would not be able to access its private field directly.
(Note to any pedants out there: Yes, I know I'm simplifying.)
You have to ask your faculty to explain why they think it's wrong (its perhaps a question of style, or even a misunderstanding), so you can learn from it.
Ultimately this person is going to impact your grades. This is an excellent opportunity to have a positive interaction with them. The more involved your teachers are with teaching you personally, the better your opportunity for mastering your subject will be.
If on the other hand when you're told something is wrong you go away privately and ask the general internet community, there is a risk that you'll be told you're right and you'll end up a false sense of superiority over your teachers which will be very counterproductive.
i detect nothing wrong.
the code works, because an instance or class can access private members of other instances of the same class. this is by design.
No, there is no problem at all with it.
Look, it depends on the viewer opinion. But for a given context this code may be just perfect.
For some other context this may not be correct. So it depends of how is going to be used.
Accessing a private member directly from another instance, is correct ( not always desirable though, for instance when you're subclassing ) that's why it is private in first place. You are saying "Hey, this is mine and I know how to use it"
Using the default access modifier for the other two methods, says that your intention is they should not be used by other classes outside the package.
Probably the only thing I would add is to make the class final.
final class Creature
If you want to make it inheritable you probably have to review the get/set for the yearOfBirth attribute, but they way it is is perfect to me.
NOW The most important thing here, is that you understand what each part of your code does, and how it affects its behavior.
You should no code just by luck ( sorry I don't know what's the correct expression for this ) but you should know what you're doing each time you type something, and how do you intend to be used.
I see two "issues," though I hesitate to call them mistakes:
You're explicitly setting Creature c's age as 89, and then rewriting that age with the uninitialized default (!) of Creature d. If this is what you intend to do, then fine, but at the very least you're wasting a few cycles to set a value that you intend to throw out later.
You're possibly violating the JavaBeans naming conventions.
To explain the latter point: a lot of Java libraries and frameworks (notably JSP) rely on JavaBeans to treat the object as a component. I haven't dived deeply into the actual mechanisms used, but from what I've read it relies on Introspection of the JavaBeans class to infer properties and the types of those properties. By overloading your setter setYearOfBirth() to accept both an int and a Creature, you could throw off the Introspection. (See here for a decent introduction to JavaBeans.)
This is not a big deal -- its entirely possible that you won't use this class as a JavaBean, and if you do it's trivial to refactor it so it works. But your teachers would probably prefer something a little cleaner, like the following:
class Creature {
private int yearOfBirth=10;
public void setYearOfBirth(int year) {
yearOfBirth = year;
}
int getYearOfBirth() {
return yearOfBirth;
}
public static void main(String args[])
{
Creature c = new Creature();
c.setYearOfBirth(89);
Creature d = new Creature();
c.setYearOfBirth(d.getYearOfBirth());
System.out.println(c.getYearOfBirth());
}
}
Now all of your access to yearOfBirth comes via the public getter methods, which helps encapsulation, and will prevent the code from breaking if your main method moves to another class. (As Greg D correctly pointed out.)
Also, this has the added benefit of making the intent of your code clear, which becomes more and more important when you start writing code for others to maintain and modify.
It's wrong because you're accessing a private member (you declared private int yearOfBirth) of another object although the class type is the same. You should use the public getter you defined instead: yearOfBirth = other.getYearOfBirth()
yearofBirth is a private int. Therefore the call to other.yearOfBirth would presumably fail...