Define the static with Object in java - java

An interviewer asked me this:
class Employee{
private string empname;
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
}
class EmpDetails{
private static Employee emp;
public static List fillData(){
emp=new Employee();
List l=new ArrayList();
System.out.println("static after new creation fillData"+System.identityHashCode(emp));
emp.setEmpname("suresh");
emp.setDesignation("Sr.Software Engineer");
l.add(emp);
emp=new Employee();
System.identityHashCode(emp);
System.out.println("static after new creation fillData"+System.identityHashCode(emp));
emp.setEmpname("Prasad");
emp.setDesignation("Software Engineer");
l.add(emp);
return l;
}
}
What happens if define below
private static Employee emp;
What is advantage with define static and non-static non access modifer with employee object?

If a field is defined static, then the value of that field is shared by all the instances of a that particular class. In your case how ever, that field is defined as private, which restricts instances of the class to access it outside the class. When your fill dataget() called it will create the list of Employee and static emp field will hold the value of the last emp("Prasad"). If any other instance of class EmpDetails is created and you try to access emp without calling fillData, using some other method e.g. GetEmp(), then it will return the last value for emp which was set to "Prasad".
With respect to design, this approach is not correct, as EmpDetails class will be pointing to one Employee due to static Employee object.

If you define a static Employee member field in theEmpDetails class - this means that all EmpDetails instances share the same Employee instance. The rest of your question doesn't really make much sense without more context.

You should consider to read up on the difference between instance variables and class variables, for example by reading the Oracle's tutorial on the topic.

Related

Gives me an error while creating an object in java

I faced an error while creating my object using a defined class in Java.
Here is my code:
public class encapsulation {
class Emp
{
int empId;
String empName;
}
public static void main(String[]args)
{
Emp e1 = new Emp();
}
}
But it gives me an error:
No enclosing instance of type encapsulation is accessible. Must qualify the allocation with an enclosing instance of type encapsulation (e.g. x.new A() where x is an instance of encapsulation).
Here is a screeshot: Error in object creation using java
You are trying to instantiate an object of an inner class. Inner class instances always need to be associated with an outer class instance. Try this -
public static void main(String[]args)
{
encapsulation en = new encapsulation();
encapsulation.Emp e1 = en.new Emp();
}
Check out the official tutorial for more info.
When you have an inner class Emp in encapsulation, any instance of Emp belongs to an instance of encapsulation. If you don't want that, make it a nested class instead, by adding a static modifier:
public class encapsulation {
static class Emp {
......
Now that Emp is declared static, it does not belong to any particular instance of encapsulation, so you don't need to instantiate encapsulation to instantiate Emp.

Why in the Student(Student s) can I use the instance variables? [duplicate]

This question already has answers here:
Why can a "private" method be accessed from a different instance?
(4 answers)
Closed 7 years ago.
So in the constructor Student(Student s) why can I use s.name? Usually when we use an object that has private instance variables we need to type s.getName() assuming a method is there to access the information. Why in this case can we use s.name, s.score1, etc.
I assume it is because it is within its own class but I cant wrap my head around why.
/**
* Manage a student's name and three test scores.
*/
public class Student {
//Each student object has a name and three test scores
private String name; //Student name
private int test1; //Score on test 1
private int test2; //Score on test 2
private int test3; //Score on test 3
/**
* Default Constructor
* Initializes name, test1, test2, and test3 to the default values
*/
public Student() {
this("", 0,0,0);
}
/**
* Constructs a Student object with the user supplying the name
* test1, test2, and test3
*/
public Student(String nm, int t1, int t2, int t3) {
name = nm;
test1 = t1;
test2 = t2;
test3 = t3;
}
/**
* Constructs a Student object with the user supplying
* a Student object as the parameter
*/
public Student(Student s){
this(s.name = "bill",s.test1,s.test2,s.test3);
}
A constructor is a member of the class, and thus can access private members, even of other instances of the class. They are private to the class, not the object. Private members can also be directly accessed from methods and property accessors.
Because public, private, and other access modifiers are specified on class-level, not in instance (object) level. So in a class, you have access to all the private members of all instances of that class; in an inherited class, you have access to all protected members of instances of that class, etc.
That makes sense because setters will definitely need access to the private members: how else can the set the fields of an instance? For constructors it is the same way.
Furthermore note that constructors sometimes are the only members that can set a field: if the field is marked final.
the keyword private in Java means that you have only access to that member if you're working inside the class. Check the following example:
public class Person {
private String name;
...
public equals(Person other) {
// You're inside the person class here, therefore you can access
// Every member of any Person object (no matter if the object is "this" or any other)
return this.name.equals(other.name)
}
}
I think the best to understand this would be to make it clear to yourself that using any class member is just the same as using it on the object this. E.g. if you write:
person = "Peter Grand";
is just the same as
this.person = "Peter Grand";
private means you can access it in your own class but not from outside the class .Since you are accessing name from within the Student class constructor it works.
The member name is declared private, which means the variable can be accessed within the scope of your own class (and therefore in all nested scopes).

Java class inside other class, constructor

I would like to create one class and then another class inside. This class will be directly connected with superior class. It should look like following (not code, just schema):
class company
string name
class employee
string firstName, lastName;
int age
Of course, I have constructors etc. Now I want to create company 'g' and employee f m of age 2 inside of that company. Maybe it is not justified to make class inside another class and I should just create class employee with field company?
Code below does not work, compiler says: an enclosing instance that contains company.employee is required
nowa=new company('g',2);
nowa.prac=new company.employee('f','m',2);
Full code below:
public class program
{
public static class company
{
char name;
int duration;
public class employee
{
public char imie,nazwisko;
public int wiek;
public employee(char a,char b,int w)
{
imie=a;
nazwisko=b;
wiek=w;
}
}
public company(char n,int c)
{
name=n;
duration=c;
}
}
public static void main(String []args)
{
company nowa=new company('g',2);
nowa.empl=new employee('f','m',2);
}
}
try
nowa.prac = nowa.new firma.pracownik('f','m',2);
Here is more on why:
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
This would be my approach
public class Employee {
//...code
}
public class Company {
//...code
private List<Employee> employees;
}
public static void main(String []args)
{
Company nowa=new company('g',2);
nowa.getEmployees.add(new Employee('f','m',2));
}
}
The main changes from your approach are:
Both classes are in its own file (both are top level classes).
Company has an List of Employees (a company HAS employees). With a List you can add and remove easily employees for a given Company.
Class names are capitalized (according to Java naming conventions by using Upper Camel Case).
Your inner class employee is not static, so you need an instance of the outer class to create an inner class instance. An employee may not exist without a company!
company nows = new company('g',2);
nowa.empl = nowa.new employee('f','m',2);
In this case the inner class instances have an implicit reference to the outer class instance (use company.this inside employee to access it).
If you want to make the classes more independent, you can make employee a status inner class without the reference to the outer class:
public static class employee
...
company nows = new company('g',2);
nowa.empl = new employee('f','m',2);

Java Inheritance with already created superclass

Lets say i have a Super class Person and subclass Employee
I would like to create a person class first and then use it as a param to be placed into my employee class's constructor.
E.g. Public Empolyee(Person person....) (This produces a constructor not found error during compile time)
My Case scenario is that i have a Person object that has not been instantiated as an employee yet and later on i would like to use it to instantiate an Employee object and I would like to pass this person's variables over.
So how do i do this? Also please do explain if it should be done this way or not.
You directly get access to all Person class members via Employee class due to the inheritance relationship. You dont need to pass parent object to a child.
Pass all the necessary parameters to Employee and call super() from its constructor.
//Person constructor
Person(param1, param2){
}
class Employee extends Person
//Employee constructor
Employee(param1, param2){
super(param1, param2);
}
// New object
Employee emp = new Employee(param1, param2);
Also constructor dont return anything so remove the void in your question.
Child class automatically gets access of all the public, protected members of the parent and child also has reference to parent class.
why you want to pass parent class reference to Child class. Instead you can call parent class constructor from child class like this:
public Child(){
super()
}
According to the question below, we can do this:
public class Child1 extends Super1 {
private int l;
public Child1(Super1 s){
super(s);
}
public Child1(){
this.l=20;
}
}
public class Super1 {
private int k;
public Super1(){
}
public Super1(Super1 s){
k=s.k;
}
}
i dont see your inheritance logic here correctly.
you have answer already..see below
class person()
class employee extends person(here)
hence you get to access its variables and methods..
just curious why you need to instantiate employee and injecting person class which is already parent to employee.
Your Employee will work as a person.You can call every method or variable (except private variables and methods) of Person by Employee object. But still if you want to pass a Person object to the constructor of Employee class then you can do it as fallows-
public Employee(Person person,.......){
super();//or pass required parameters according to constructor of Person class
//do whatever you want
}
it will work perfectly.
try this:
//if your Person constructor looks like this
public Person(param1, param2){
}
//then your copy constructor would look like this
public Employee(Person p){
super(p.getParam1 p.getParam2);
}

Access Methods of a class from created object of another class

I need little help here. I have three classes Book, Member, Bean.
Book.java
public class Book
{
public Member m=null;
// various getter & setter methods
}
Member.java
public class Member
{
public Book b=null;
// various getter & setter methods
}
In Bean.java I create an object of Book class & through this object we have to access all methods of Book as well as Member class.Now the problem is the object of Member class created in Book is not initialized & we can't use new operator to initialize it & we can't make it static. If we use new operator the result is not come.
This design is not correct.
There is a circular dependency.
Book has a Member and Member has a Book .
You need to double check this design.
Constructor injection would be the easiest way to fix this once you have the dependencies sorted out.
UPDATE : Corrected design which I feel is correct.
//Book
public class Book {
private String bookName;
private String authorName;
//getters and setters
}
//Member will have a book (maybe multiple) associated with them
public class Member {
private Book[] bookArray;
public Member (Book... books) {
this.bookArray = books;
}
}

Categories

Resources