How to access private data member outside the class? - java

I am trying to access the private data member of inner class outside the outer class.
Please help me?

You don't - that's the whole point of it being private.
The inner class can expose the data via a property, of course:
public class Outer {
public class Inner {
private final String name;
public Inner(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
public class Other {
public void foo() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner("Foo");
// Can't access inner.name here...
System.out.println(inner.getName()); // But can call getName
}
}
... but if the inner class wants to keep it private, then you shouldn't try to access it.

Create public getter setter methods inside the inner class for private variables. Then create an object and call them to access private data. You can't directly access private data.

you cant access a private data. If ýou have other thoughts of accessing it use public getter method returning that private data.

you can access private data member using getter method ex
package pack;
import java.io.ObjectInputStream.GetField;
public class abc {
private int num = 2;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
class otherClass {
public static void main(String[] args) {
abc obj = new abc();
System.out.println(obj.getNum());
}
}

Related

Java Subclass error: No enclosing instance of type is accesible

I'm attempting to create a class Person with a subclass Employee, and I get No enclosing of type error. I've tried to google how basic classes and sub classes are portrayed and it's always 'simple' the same way I write it so I'm probably mistaking something else.
Minimal as I understand, as requested.
import com.Person.Employee;
public class Main {
public static void main(String[] args) {
Employee test = new Employee();
}
}
package com;
public class Person {
private String name;
public Person() {
name = "";
}
public class Employee extends Person {
private float personalID;
public Employee(){
super();
personalID = 0;
}
}
}
error: No enclosing instance of type Person is accessible. Must qualify the allocation with an enclosing instance of type Person (e.g. x.new A() where x is an instance of Person)

Java: Calling a parent's method with child's member variable

Let's say I have an abstract parent class that has member variables which are used in a method.
public abstract class Person{
public String jobTitle;
public void printJob(){
System.out.println(jobTitle);
}
}
If I now have two child classes
public class Teacher extends Person{
public String jobTitle = "Teacher";
}
public class Janitor extends Person{
public String jobTitle = "Janitor";
}
and I want to avoid code cloning, i.e. implementing the same printJob()-method in both classes, I now have a problem, since the printJob()-method is unable to access member variables of the child classes.
Is there any way that i can call a parent classes' method but have the method use the child classes' member variables?
You can use abstract methods like this
public abstract class Person {
public void printJob() {
System.out.println(getJobTitle());
}
protected abstract String getJobTitle();
public static void main(String[] args) {
Person teacher = new Teacher();
Person janitor = new Janitor();
System.out.println(teacher.getJobTitle());
System.out.println(janitor.getJobTitle());
}
}
class Teacher extends Person {
#Override
protected String getJobTitle() {
return "Teacher";
}
}
class Janitor extends Person {
#Override
protected String getJobTitle() {
return "Janitor";
}
}
Updated after op's comment for code cloning...
public class Person {
public static void main(String[] args) {
System.out.println(new Teacher().job);
System.out.println(new Janitor().job);
}
private static class Teacher extends Person {
private String job = "Teacher";
}
private static class Janitor extends Person {
private String job = "Janitor";
}
}

Initialize a class having another class object as member variable

This is my first class:
package trickycorejava;
public class InnerClass {
int id;
oneClass oneClass;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public trickycorejava.oneClass getOneClass() {
return oneClass;
}
public void setOneClass(trickycorejava.oneClass oneClass) {
this.oneClass = oneClass;
}
public InnerClass(int id, trickycorejava.oneClass oneClass) {
this.id = id;
this.oneClass = oneClass;
}
public InnerClass(int id){
this.id = id;
}
}
class oneClass {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is the class where the main method exists, observe that the package is different:
package trickycorejava.constructor;
import trickycorejava.InnerClass;
public class InnerClassTest {
public static void main(String[] args) {
InnerClass innerClass = new InnerClass(1);
}
}
How can I initialize the InnerClass with constructor in this case? If I use
InnerClass innerClass = new InnerClass(1, new oneClass("Test"));
I get the error that oneClass is not public cannot be access from outside package.
As Turing85 pointed out the oneClass should be in it's own file, otherwise it's going to be package-private which means you can only access it from classes of the same package.
Is there another way? There is, but it's not going to be a simple constructor call. Using reflection you can bypass class, field and method invocation protection.
public class InnerClassTest {
public static void main(String[] args) throws Exception {
Constructor<OneClass> constructor = OneClass.class.getDeclaredConstructor(String.class);
constructor.setAccessible(true);
OneClass instance = constructor.newInstance("John");
InnerClass innerClass = new InnerClass(1, instance);
}
}
What this does is that it finds the constructor that is private to Main because the class is package-private. Then it disables the protection of it, note that these are temporary, the Constructor object is a new reference and only allows the invocation via this reference.
But I don't recommend doing this extensively. Reflection has some use cases, mainly to aid programmers in frameworks like Spring, but otherwise it can break object oriented patterns.

java - sending variables through nested classes

I have a class that has a variable of type Name.
public class Holder {
private Name name;
private int snumber;
The Name class has two strings called first and last that are assigned values by setter methods. I would like to send over the strings from the Name class to name in the Holder class, but I'm having trouble doing so. I think I've taken a step in the right direction by doing this
public class Holder {
private Name name;
private int snumber;
public void setName(){
name = new Name();
name.getFirst();
name.getLast();
}
but I can't say that I really know what the correct approach is. I also tried name.setFirst(getFirst) but that doesn't work. Any ideas would be appreciated.
The same way you would if the class wasn't nested.
Your setName() method should take a parameter (maybe 2, first and last) and then invoke the name.setFirstName(), name.setLastName() methods.
Right now, your setName() method isn't doing anything.
E.G:
public class Holder
{
private Name name;
private int snumber;
public Holder()
{
this.name = new Name();
}
public void setName(String firstName, String lastName)
{
this.name.setFirst(firstName);
this.name.setLAst(lastName);
}
}
Here is a good article explaining the relationship between Java inner and outer classes:
https://www.tutorialspoint.com/java/java_innerclasses.htm
class Outer_Demo {
// private variable of the outer class
private int num = 175;
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2 {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Instantiating the inner class
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}
Note that the example creates instances of both "Outer_Demo" AND "Inner_Demo (outer.new Inner_Demo();).
Ok, so I figured something out that works.
public class Holder {
private int snumber;
private Name name;
public void setName(Name n){
name=n;
}
public Name getName(){
return name;
}

Eclipse throwing error on invalid modifiers, rename in file

I'm a beginner in Java and I was typing this block of code in Eclipse and it is throwing errors like this. I haven't even started anything yet, but there's error with my variable name? I know Eclipse is very particular about duplicate variable names in maybe the same package or something. Is that maybe where the problem is?
Thanks!
You need to either declare those variables outside the main method (if you want them to have class scope), or remove the private keyword if you want them to have method scope, i.e. just in your main method.
So either this:
public class Person {
private String name;
// other variables...
public static void main(String[] arguments) {
// other code...
}
}
Or like this:
public class Person {
public static void main(String[] arguments) {
String name;
// other variables and code...
}
}
You can not use the access modifier private inside any method. Remove the access modifier private before the variable name.
Or you can declare these variable in class level (that is as instance variables) - outside of any methods. Since the name is a property/attribute of a Person, according to OOP it is better to keep the name as field of the Person class like this -
public class Person{
private String name;
//Other property of Person
public String getName(){
return name;
}
public String setName(String name){
this.name = name;
}
public static void main(String[] args){
}
}
Use public getter and setter method to access these private variable from outside of the Person class.
Either do this:
public class Person {
private String name; // Declared as an attribute of Person class
public static void main(String [] args) { ...}
}
Or this:
public class Person {
public static void main(String [] args) {
String name; // No private
// ...
}
}
Just remove the access modifier private in both the variables.Your problem
will be solved.You cannot declare private variables inside methods.

Categories