Java Assignment
1) Animal Class in Java
Java code to create an Animal class with attributes species and sound. Includes methods to
get and set these attributes, instantiate an object, and access its members.
// Animal.java
public class Animal {
private String species;
private String sound;
public Animal(String species, String sound) {
this.species = species;
this.sound = sound;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public String getSound() {
return sound;
}
public void setSound(String sound) {
this.sound = sound;
}
public void display() {
System.out.println("Species: " + species);
System.out.println("Sound: " + sound);
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal("Dog", "Bark");
myAnimal.display();
myAnimal.setSpecies("Cat");
myAnimal.setSound("Meow");
myAnimal.display();
}
}
Assignment Questions
1. Explain the concept of a class and an object in Java with a real-world analogy.
A class is like a blueprint for creating objects. It defines the structure and behavior
(attributes and methods). An object is an instance of a class.
Real-world analogy: Think of a class as a 'Car blueprint', and an object as an actual car made
from that blueprint. Multiple cars (objects) can be created from the same blueprint (class),
each with its own values (color, speed).
2. What are the different categories of data types in Java, and how do they
differ from each other?
Java has two main categories:
1. Primitive Data Types:
- Includes: byte, short, int, long, float, double, char, boolean
- These are predefined by the language and hold simple values.
2. Non-Primitive (Reference) Data Types:
- Includes: String, Arrays, Classes, Interfaces
- They store references to objects, not the actual data itself.
Differences:
- Primitives are faster and require less memory.
- Reference types can store more complex data and behaviors.
3. What is the default value assigned to different primitive data types in Java if
not explicitly initialized?
Data Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
Note: These default values apply to instance variables, not local variables.
4. What are the different types of variable scopes in Java? Explain each with an
example.
1. Local Variables:
- Declared inside a method or block and only accessible there.
Example:
void method() {
int localVar = 5;
}
2. Instance Variables:
- Declared inside a class but outside methods. Each object gets its own copy.
Example:
public class Demo {
int instanceVar = 10;
}
3. Class/Static Variables:
- Declared with static. Shared among all instances of the class.
Example:
public class Demo {
static int staticVar = 20;
}