Java Class, Objects, Methods, Constructor example – part 1


 1. Example 1:

class Bird{
int flying_height;
String color;
}
class A{
public static void main(String[] args){
Bird b=new Bird();
b.flying_height=728;
b.color=”red”;
System.out.println(b.flying_height);
System.out.println(b.color);
}
}

Note*: Save, Compile and Execute the program.
Output:
728
red

2. Example 2:

class Bird{
int flying_height;
String color;

void display(){
System.out.println(“Flying height: “+flying_height);
System.out.println(“Color: “+color);

}
}

class A{
public static void main(String[] args){
Bird b=new Bird();
b.flying_height=728;
b.color=”red”;
b.display();

}
}
Note*: Save, Compile and Execute the program.
Output:
Flying Height: 728
Color: red

3. Example 3:

class Bird{
int flying_height;
String color;

void display(){
System.out.println(“Flying height: “+flying_height);
System.out.println(“Color: “+color);

}
}

class A{
public static void main(String[] args){
Bird b=new Bird();
b.flying_height=728;
b.color=”red”;
b.display();
Bird b1=new Bird();
b1.display();
b.display();
}
}
Note*: Save, Compile and Execute the program.
Output:
Flying Height: 728
Color: red
Flying Height: 0
Color: null
Flying Height: 728
Color: red

4.  Example 4:

class Bird{
static int flying_height;
static String color;

void display(){
System.out.println(“Flying height: “+flying_height);
System.out.println(“Color: “+color);

}
}

class A{
public static void main(String[] args){
Bird b=new Bird();
b.flying_height=728;
b.color=”red”;
b.display();
Bird b1=new Bird();
b1.display();
}
}
Note*: Save, Compile and Execute the program.
Output:
Flying Height: 728
Color: red
Flying Height: 728
Color: red

5. Example 5.

class Bird{
static int flying_height;
static String color;

static int height=100;
static String name=”sparrow”;

}

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

System.out.println(“Flying height: “+Bird.flying_height);
System.out.println(“Color: “+Bird.color);

System.out.println(“Flying height: “+Bird.height);
System.out.println(“Color: “+Bird.name);

}
}

Note*: Save, Compile and Execute the program.
Output:
Flying Height: 0
Color: null
Flying Height: 100
Color: sparrow