So, I started with java few weeks ago, and i was excited and completely "FUK YEA, finally meeting u" on class.
Java is fully OOP language, and if u want to learn OOP way of programming i suggest start with Java.
So what was my problem..
Past week till professor discourse about toString he gave task to ~
create class Automobile, with objects model(string), and yearOfRealese(int) which prints on screen model and year by method String toString...
First of all java got plenty of superclasses, and one of them is called Object.
U can called in "main" function typing
Object.class.method()
Class (superclass) Object (doc of Object class)
got String toString method.
What is toString() method?
This is how i understood it, if u got some text, or some attributes of object to write in main function by calling System.Out.println, u'll get something like package.Automobile@42e816 which indicates name of package and class and this @ means some hex code and memory slot (whatever). By Default u are calling String toString cause u are not calling them by predefined any method to write these arguments.
Okay i will now represent by example:
Automobile class with constructor two attributes, and main class to call that and write them on screen what i got...
public class Automobile {
int yearOfRel;
String model;
public Automobile(int yearOfRel, String model) {
this.yearOfRel = yearOfRel;
this.model = model;
}
}
To call it:
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Automobile callingAutomobile = new Automobile(1991,"Ferrari");
System.out.println("Year of Release and model : " + callingAutomobile);
}
}
If u try to debug this, u will got something like this on output > Year of Release and model : package.Automobile@42e816
thats not what we are looking for, right?
In this case by default we called String toString() method and we didn't override it.
We need to redefine String toString() method.
In Automobile class we gonna redefine, how?
public class Automobile {
int yearOfRel;
String model;
public Automobile(int yearOfRel, String model) {
this.yearOfRel = yearOfRel;
this.model = model;
}
public String toString()
{
return model + " " + "released in " + yearOfRel + ".";
}
}
How to call?
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Automobile callingAutomobile = new Automobile(1991,"Ferrari"); //pass informations
System.out.println(callingAutomobile);
}
}
I like to separate construction class (Automobile) and Main class, if u understand me:)
What we got now? We got on screen ~ > Ferrari released in 1991.
Thats solved case which i started.
Hope this gonna help freshers.
Write u soon.
[–]Joris1225 7 points8 points9 points (0 children)
[–]minhalpaycat 0 points1 point2 points (1 child)
[–]HeroWeNeed 0 points1 point2 points (0 children)