Loading subject…
class Bird: # Constructor: runs automatically when a Bird is created def __init__(self, species, age): self.species = species # instance variables self.age = age
# Method (behaviour) def sing(self): print(f"{self.species} is singing!")
# Accessor def get_age(self): return self.agepublic class Bird { // Instance variables, private so they are encapsulated private String species; private int age;
// Constructor: same name as the class, no return type public Bird(String species, int age) { this.species = species; this.age = age; }
// Method (behaviour) public void sing() { System.out.println(species + " is singing!"); }
// Accessor public int getAge() { return age; }}# Instantiation: each call to Bird(...) builds a separate objectsparrow = Bird("Sparrow", 2)parrot = Bird("Parrot", 5)
sparrow.sing() # Sparrow is singing!parrot.sing() # Parrot is singing!print("Parrot age:", parrot.get_age()) # Parrot age: 5
# The two objects are independentparrot.age = 6print(sparrow.get_age(), parrot.get_age()) # 2 6public class Main { public static void main(String[] args) { // Instantiation: new allocates memory and calls the constructor Bird sparrow = new Bird("Sparrow", 2); Bird parrot = new Bird("Parrot", 5);
sparrow.sing(); // Sparrow is singing! parrot.sing(); // Parrot is singing! System.out.println("Parrot age: " + parrot.getAge()); // Parrot age: 5
// The two objects are independent System.out.println(sparrow.getAge() + " " + parrot.getAge()); // 2 5 }}class Bird: def __init__(self, species="Unknown", age=0): self.species = species self.age = age
b1 = Bird() # uses both defaultsb2 = Bird("Robin") # uses the default age onlyb3 = Bird("Owl", 3) # supplies both
print(b1.species, b1.age) # Unknown 0print(b2.species, b2.age) # Robin 0print(b3.species, b3.age) # Owl 3public class Bird { private String species; private int age;
// No-argument constructor, written explicitly public Bird() { this.species = "Unknown"; this.age = 0; }
// Parameterised constructor public Bird(String species, int age) { this.species = species; this.age = age; }}
// Bird b1 = new Bird(); species "Unknown", age 0// Bird b2 = new Bird("Owl", 3); species "Owl", age 3