Solution Review: Declaring Class Attributes
The solution to the Class Attributes Declaration exercise is explained in this lesson.
We'll cover the following...
Coding solution
Let’s have a look at the code first:
Press + to interact
/*Member variables can be declared inside class, but outside any methodThere are four types of access modifiers1) public = it is available in package, subclass, and outer world2) protected = it is available in package, subclass, and not in the outer world3) private = it is not available in package, subclass, and outer world4) default (no modifier) = it is only available in package*//*In this program we will check the access modifiers individually*/class FatherPanda {public boolean isPredator;protected int weight;private int age;public void eat() {System.out.println("After each meal, Father Panda gains weight: " + weight);System.out.println( "His age is: " + age);}}public class ClassChallenge {public static void main(String [] args) {FatherPanda father = new FatherPanda();// father.isPredator = true;System.out.println("Is father panda predator. " + father.isPredator);father.weight = 5;father.eat();// we cannot modify private member variable this way, it will give error// father.age = 10;}}
Explanation
In the above code, we have commented out this line:
// father.age = 10;
Otherwise, it produces ...