Objects



Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.


  1. Syntax for an Object in Java
  2. Create an Object for a Class in Java
  3. Accessing Variables using Object in Java
  4. Accessing Methods using Object in Java

A. Syntax for an Object in Java

ClassName.java

public class ClassName {

// Initialise Variables
public ClassName() {
// Write Code Inside Constructor
}
}

class MainClassName {
public static void main(String args[]) {
ClassName ObjectName = new ClassName();
}
}




B. Create an Object for a Class in Java

Object_Ex1.java

public class Object_Ex1 {

int a = 10;
int b = 20;
int c;
public Object_Ex1() {
c = a + b;
System.out.println("The Addition is : "+c);
}
}

class MainClass {
public static void main(String args[]) {
Object_Ex1 obj = new Object_Ex1();
}
}

Sample Output

The Addition is : 30




C. Accessing Variables using Object in Java

Objext_Ex2.java

public class Objext_Ex2 {
int a = 10;
float b = (float)56.23;
String str = "Java";
}

class MainClass {
public static void main(String args[]) {
Objext_Ex2 ObjectName = new Objext_Ex2();
System.out.println("The Integer Value is : "+ ObjectName.a);
System.out.println("The Float Value is : "+ ObjectName.b);
System.out.println("The String Value is : "+ ObjectName.str);
}
}

Sample Output

The Integer Value is : 10
The Float Value is : 56.23
The String Value is : Java




D. Accessing Methods using Object in Java

Objext_Ex3.java

public class Object_Ex3 {
int a;
float b;
String str;

public Object_Ex3() {
a = 100;
b = (float)10.20;
str = "Open Source";
}
public void Method() {
System.out.println("The Integer Value is : "+ a);
System.out.println("The Float Value is : "+b);
System.out.println("The String Value is : "+str);
}
}

class MainClass {
public static void main(String args[]) {
Object_Ex3 ObjectName = new Object_Ex3();
ObjectName.Method();
}
}

Sample Output

The Integer Value is : 100
The Float Value is : 10.2
The String Value is : Open Source


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.