class properties and methods in java

Create class properties

class Person{
int age=40;
String name="Aman";
}

Accessing class properties

class Person{

int age=40;
String name="Aman";

public static void main(String ar[]){
Person p=new Person();
System.out.print(p.age);
System.out.print(p.name);
}
}
 

Change class properties

class Person{
int age=40;

public static void main(String ar[]){
// create new object
Person p = new Person();
// access properties
System.out.print(p.age);
// change properties
p.age=45;
// access properties again
System.out.print(p.age);
}

}

Methods in java

In java, methods have two types, Static and Non-Static.

Non-static methods

Methods are not declared with static keywords and required an object to access methods is called the non-static method.

class Person{

String name;
int age;

void display(){
System.out.println("Name:"+name);
System.out.println("Age:"+age);
}

public static void main(String ar[]){
Person p = new Person();
p.display();
}

}

Static methods

Methods declared with a static keyword and do not require an object to access methods is called static method.

class Person{

String name;
int age;

static void display(){
System.out.println("Name:"+name);
System.out.println("Age:"+age);
}

public static void main(String ar[]){
display();
}

}
© 2016 - 2022, All Rights are Reserved.