Posts Tagged object
Java Tutorial 12 – Constructors
constructors are a special type of method which we can use to initialize Objects when we create it. If u do not use constructor, objects contains all the variables and methods, But Using constructor you can initialize values of variables. For example you can initialize some variables to zero or Strings to default values and etc. Lets Clear this with an example. Create two classes Tom and Jerry.
Tom:
public class Tom {
public static void main(String[] args){
Jerry object = new Jerry();
object.print();
}
}
Jerry:
public class Jerry {
int a;
String b;
public void print(){
System.out.println(“int a = “+a);
System.out.println(“String b = “+b);
}
}
Now if u run the Tom.java you will see the output like:
int a = 0
String b = null
Now if you want to initialize String b to some text say “Hi” and int a to value 5 whenever the new object is created, you can do it by creating constructor. There are some rules for it:
- Name of the constructor must be same as name of class.
- there is no other rule 😛
Now lets create constructor for Jerry class and initialize variables.
Jerry:
public class Jerry {
int a;
String b;
Jerry(){
a=5;
b = “Hi”;
}
public void print(){
System.out.println(“int a = “+a);
System.out.println(“String b = “+b);
}
}
!!!!! yap writing return type and access modifiers is optional. We can define Constructor by just Jerry(){ … }.
Now if you run the Tom.java you will see the output like:
int a = 5
String b = Hi
Here constructor initialized both variables when we created an object of Jerry.
catch you again later…
doubts are invited.
have a nice day.
Peace.
Java Tutorial 6 – Multiple class methods
If u want to make more complex and big application You should divide your whole code into different classes.
for example if you are creating a Calculator you can have a class that holds main method and another class which contains all operations like add, sub, multiply etc. and when dealing with GUI you can also have one more class for defining all the GUI elements like buttons, Textfields etc.
(maan plz stop talking…)
- Create 2 classes whatever you want.
- create main method in one class.
- create methods that you want to use in other class.
Like this way
Class1:
Class 2:
- We have created 2 classes one has methods and other will use it.
- class 1 has main method that will be run first and class 2 has methods that we will use in class 1
- class 2 has 2 methods boy() and girl()
- Now to access method of class2 we created object of class2 in class 1 that is c2object.
- now only we have to do is to refer method of class 2 bye calling object.method() means if u want to use girl() then c2object.girl().
- you can name object anything you want.
- if you have an int in class2, you can also use it by referring c2object.intname
Practice more and implement different logic to improve you speed and accuracy.
Have a nice day, Peace.

