Friday, January 29, 2016

public class JavaClass { public static void main(String[]args){ } }

Classes and Methods:
A class is a set of rules that will define an object in a later program, they are made to hold methods which are consequently the rules that formulate every object and these methods are written with different parameters and manipulated to benefit the code.
Ex. of a class:
public class Blog{

}
this will be what contains the rules and settings to create an object called Blog. They are usually started with a capital letter and are written with brackets which are what holds the code inside of the class.
Ex. of methods:
public class Blog{
int amountOfPosts
  public static void main(String[]args){

  Blog myBlog = new Blog(2);
  Blog myBlog2 = new Blog();

  //Will do the same as myBlog
  myBlog.setAmountOfPosts(3);

  }
  public Blog(){
  }
  public Blog(int a){
  amountOfPosts = a;
  }
}
the main method is the most important method in Java programming, it helps define where a program starts and inside of it's brackets is where the program should be defined for the JRE(Java Run-time Environment) to read and run the program. The parameter of String[]args inside the parenthesis next to main is in itself quite complicated, it is an array of Strings that are assigned to variable args, it helps the program know that it is running.
public Blog() is a method that is defined as a Constructor, it defines what an object of class Blog must have when it is defined. In this case myBlog is an object of class Blog and has an amountOfPosts of two, this is assigned in the parenthesis next to Blog when creating a new object
and is ultimately assigned on the constructor, if the parameter of an object is empty such as myBlog2 it will use the constructor that has the same parameters.
There are different ways of writing a method that have to do with encapsulation (private, public, protected) but there is different types of methods as well depending on whether you want a return or not.
public void setAmountOfPosts(int a){
  amountOfPosts = a;
}
this method will not give you a return because is a void method, this means that it does not by itself hold to any data but it will modify the program in any way you want
public static String getATitle(String t){
int title = t;
return title;
}
this is a method that requires a return because it holds on to data, in this case is a String data. It is not required to use the static modifier but for this type of method it is recommended because of recursion (Will probably write another post about this theme.)

3 comments:

  1. Another great read explaining Java thanks Cesar!

    ReplyDelete
  2. i just love how you only talk bout java. This blog is great.

    ReplyDelete
  3. i just love how you only talk bout java. This blog is great.

    ReplyDelete