...

/

Solution Review: Declaring Class Attributes

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 method
There are four types of access modifiers
1) public = it is available in package, subclass, and outer world
2) protected = it is available in package, subclass, and not in the outer world
3) private = it is not available in package, subclass, and outer world
4) 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 ...