class keyword in Java
The class
keyword is used to declare a new Java class, which is a collection of related variables and/or methods.
Classes are the basic building blocks of object−oriented programming.
A class typically represents some real−world entity such as a geometric Shape or a Person.
A class is a template for an object. Every object is an instance of a class.
To use a class, you instantiate an object of the class, typically with the new
operator, then call the methods to access the features of the class.
Class will be defined with access specifier as either public
or default
only.
We can’t make class as private
or protected
(can be done only for inner classes)
Example 1
- public class Rectangle
- {
- float width;
- float height;
- public Rectangle(float w, float h){
- width = w;
- height = h;
- }
- public float getWidth(){
- return width;
- }
- public float getHeight(){
- return height;
- }
- }
public class Rectangle { float width; float height; public Rectangle(float w, float h){ width = w; height = h; } public float getWidth(){ return width; } public float getHeight(){ return height; } }
Example 2
- public class Person
- {
- String name;
- int age;
- public int getAge() {
- return age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name){
- this.name = name;
- }
- public void setAge(String age) {
- this.age = age;
- }
- }
public class Person { String name; int age; public int getAge() { return age; } public String getName() { return name; } public void setName(String name){ this.name = name; } public void setAge(String age) { this.age = age; } }