- In Java programs, classes are the basic building blocks. While defining a class we define all the parts and characteristics of that building blocks. For using most classes we have to create objects.
- An Object is a runtime instance of a class in memory. All the different objects of all the different classes represent the state of our program.
Fields and Methods -
- Java classes have two primary elements :-
- methods - often called as function and procedures in other languages.
- field - generally known as variable.
- Together these are called members of the class.
- Variable holds the state of the program and method operate on that state.
- This is the basically classes do.
- Below is the simple java class-
}
- Java calls a word with special meaning keyword.
- The public keyword means the class can be used by other classes.
- class keyword is used to define a class.
- Animal gives the name of the class.
- Now, we'll add a field to the class.
public class Animal{
String name;
}
- We define a variable named name. We also define the type of that variable to be a String(It is a value that we can put text into, such as "This is a String".
- String is also a class supplied with Java.
- Now, we'll add methods to our class.
public class Animal{
String name;
public String getName(){
return name;
}
public void setName(String newName){
name = newName;
}
}
- Here we defined our first method( a method is an operation that can be called).
- Again, public is used to signify that this method may be called from other classes.
- return type - in this case, the method returns a String.
- In second method has a special return type called void( void means that no value at all is returned.)
- This method requires information be supplied to it from calling method; this information is called a parameter. setName has one parameter named newName, and it is of type String. This means the caller should pass in one String parameter and expect nothing to be returned.
No comments:
Post a Comment