1. 접근지정자 개념과 종류 : 클래스내에서 멤버(멤버변수, 멤버메서드)의 접근을 제한하는 역할
- 접근지정자의 종류
분류 | 클래스내부 | 동일패키지 | 상속관계 | 모두 |
public | o | o | o | o |
protected | o | o | o | o |
default | o | o | ||
private | o |
2. 멤버변수 접근지정자
class Parent{
(default) String name="홍길동";
public int age = 40;
protected int height = 170;
private int weight = 68;
}
class Child extends Parent{
public static void main(String[] args){
Child c = new Child();
System.out.printIn(c.name); //홍길동 default는 상속관계에서 사용x인데 왜???
System.out.printIn(c.age); //40
System.out.printIn(c.height); //170(상속o, 사용o)
System.out.printIn(c.weight); //Error
}
}
3. 메서드 접근지정자
class Parent{
String name="홍길동";
private int weight = 68;
public int get_weight; //private인 weight를 사용하기 위해서
return this.weight;
}
public void set_weight(int parent_weight){ //private인 weight를 사용하기 위해서
this.weight = param_weight;
}
}
class Child extends Parent{
public static void main(String[] args){
Child c = new Child();
c.set_weight(70);
System.out.printIn(c.name);
System.out.printIn(c.get_weight());
}
}
//홍길동
//70
다음 자바코드를 컴파일할때, 문법오류가 발생하는 부분은?
class Person{
private String name;
public int age;
public void setAge(int age){
this.age = age;
}
public String toString(){
return("name:" + this.name + ",age:" + this.age);
}
}
public class PersonTest{
public static void main(String[] args){
Person a = new Person(); //1
a.setAge(27); //2
a.name="Gildong"; //3
System.out.printIn(a); //4
}
}
다음 프로그램의 A3클래스에서 사용할 수 있는 객체 변수들로 옳은것은?
pulbic class A1{
public int x;
private int y;
protected int z;
}
public class A2 extends A1{
protected int a;
private int b;
}
public class A3 extends A2{
private int q;
}
//x,z,a,q
반응형
'정보처리기사 > [흥달쌤] 실기_JAVA 특강 (완)' 카테고리의 다른 글
JAVA특강 / 07. 추상클래스&Interface (0) | 2022.04.29 |
---|---|
JAVA특강 / 06. Static (0) | 2022.04.29 |
JAVA특강 / 04. 메서드 오버로딩&오버라이딩 (0) | 2022.04.29 |
JAVA특강 / 03. 상속 (0) | 2022.04.29 |
JAVA특강 / 02. 생성자&예외 (0) | 2022.04.28 |