Here we will cover very basic of Class , will not see much into its modifiers. This is to just get Java programming started.
Below is basic structure using which you can write your code.
public class classname{
// varibales declaration
// for class variables use static modifier
// for object variables do not use static modifier
// method (functions) can be defined
public static int main(String args[]) {
}
}
Points to note : classname should be same as filename with which you are saving the file
In one file you can have multiple classes but only one should be PUBLIC.
main method will always be PUBLIC and STATIC.
The other beauty of Java is you have to define and access classes. You can't do anything without them.
Ex the below program is simple and I was writing it to tell that in ONE FILE , you can have only one PUBLIC class, but it was not working .
public class global1{
static int global=2;
public static void main(String args[])
{
System.out.printtln(global);
System.out.println(global12.adder(global));
}
}
class global12{
public int adder(int a)
return a+2;
}
}
// It will throw error non-static method can't be access from static method.
So we cannot simply learn syntax and start coding like C .
CLASSES needs to be define. THE below CODE works fine
public class global1{
static int global=2;
public static void main(String args[])
{
global1 my = new global1();
global12 ur = new global12();
System.out.printtln(my.global);
System.out.println(ur.adder(global));
}
}
class global12{
public int adder(int a)
return a+2;
}
}
Below is basic structure using which you can write your code.
public class classname{
// varibales declaration
// for class variables use static modifier
// for object variables do not use static modifier
// method (functions) can be defined
public static int main(String args[]) {
}
}
Points to note : classname should be same as filename with which you are saving the file
In one file you can have multiple classes but only one should be PUBLIC.
main method will always be PUBLIC and STATIC.
The other beauty of Java is you have to define and access classes. You can't do anything without them.
Ex the below program is simple and I was writing it to tell that in ONE FILE , you can have only one PUBLIC class, but it was not working .
public class global1{
static int global=2;
public static void main(String args[])
{
System.out.printtln(global);
System.out.println(global12.adder(global));
}
}
class global12{
public int adder(int a)
return a+2;
}
}
// It will throw error non-static method can't be access from static method.
So we cannot simply learn syntax and start coding like C .
CLASSES needs to be define. THE below CODE works fine
public class global1{
static int global=2;
public static void main(String args[])
{
global1 my = new global1();
global12 ur = new global12();
System.out.printtln(my.global);
System.out.println(ur.adder(global));
}
}
class global12{
public int adder(int a)
return a+2;
}
}
No comments:
Post a Comment