Skip to content

Commit 22deaaa

Browse files
NickTononiashleyfrieze
authored andcommitted
[BAEL-3147] Java 'protected' modifier (eugenp#7886)
* [BAEL-3147] Java 'protected' modifier * updated README.md * Update README.md * Update SecondGenericClass.java
1 parent 04dc9dd commit 22deaaa

File tree

4 files changed

+71
-0
lines changed

4 files changed

+71
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baeldung.core.modifiers;
2+
3+
public class FirstClass {
4+
5+
protected String name;
6+
7+
protected FirstClass(String name) {
8+
this.name = name;
9+
}
10+
11+
protected String getName() {
12+
return name;
13+
}
14+
15+
protected static class InnerClass {
16+
public InnerClass() {}
17+
}
18+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.core.modifiers;
2+
3+
public class GenericClass {
4+
5+
public static void main(String[] args) {
6+
// accessing protected constructor
7+
FirstClass first = new FirstClass("random name");
8+
// using protected method
9+
System.out.println("FirstClass name is " + first.getName());
10+
// accessing a protected field
11+
first.name = "new name";
12+
// instantiating protected inner class
13+
FirstClass.InnerClass innerClass = new FirstClass.InnerClass();
14+
}
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baeldung.core.modifiers.otherpackage;
2+
3+
import com.baeldung.core.modifiers.FirstClass;
4+
5+
public class SecondClass extends FirstClass {
6+
7+
public SecondClass(String name) {
8+
// accessing protected constructor
9+
super(name);
10+
// using protected method
11+
System.out.println("SecondClass name is " + this.getName());
12+
// accessing a protected field
13+
this.name = "new name";
14+
// instantiating protected inner class -> add public constructor to InnerClass
15+
FirstClass.InnerClass innerClass = new FirstClass.InnerClass();
16+
}
17+
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.core.modifiers.otherpackage;
2+
3+
import com.baeldung.core.modifiers.FirstClass;
4+
//import com.baeldung.core.modifiers.FirstClass.InnerClass;
5+
6+
public class SecondGenericClass {
7+
8+
// uncomment the following lines to see the errors
9+
public static void main(String[] args) {
10+
// accessing protected constructor
11+
// FirstClass first = new FirstClass("random name");
12+
// using protected method
13+
// System.out.println("FirstClass name is " + first.getName());
14+
// accessing a protected field
15+
// first.name = "new name";
16+
// instantiating protected inner class
17+
// FirstClass.InnerClass innerClass = new FirstClass.InnerClass();
18+
}
19+
20+
}

0 commit comments

Comments
 (0)