Java日记(3)

封装类,可以联想以下c语言的结构体;定义类,定义其属性、方法的过程称为封装类。

class Students
{
	int age;
	String name;//Java中没有char,所以字符型用String
	double score;
	//上面定义了数据,以下要定义方法
	void introduce()//在类里的方法一般不用参数,它会自动去类里的数据查找
	{
		System.out.println(name+"今年"+age+"岁"+",本学期考了"+score+"分");
	}
	void testFunc()
	{
		System.out.println("testFunc");
	}
}
//以上便实现了对数据和方法的封装
public class demo_1 {
	public static void main(String[] args) {
		//可以形象的把类比作为c语言的结构体,类的调用如下,与结构体相似
		Students stu1 = new Students();//该句既定义了一个类,也为改类开辟了空间,类比c预言的操作,如下:
		/*Struct Students *stu1;
		stu1 = malloc(sizeof(Struct Strudents));*/
		stu1.age = 20;
		stu1.name = "xiao ming";
		stu1.score = 100.0;
		stu1.introduce();//调用类里面的方法
		}
}

访问修饰符:private、protected、public、默认 这四种,访问权限如下

位置private默认protectedpublic
同一个类

同一个包内的类
不同包内的类
不同包并且不是子类

 

 以下代码基于上一个代码,在类中增加了体重这个数据,并设置为private,发现在另一个类中无法通过stu1.来获取体重这个数据,只能在类中造一个方法(函数)来jian'jie'fang'w

class Students
{
	int age;
	String name;//Java中没有char,所以字符型用String
	double score;
	private double weight;
	void seeweight(double wei)
	{
		weight = wei;
	}
	void introduce()//在类里的方法一般不用参数,它会自动去类里的数据查找
	{
		System.out.println(name+"今年"+age+"岁"+",本学期考了"+score+"分,体重是"+weight);
	}
	void testFunc()
	{
		System.out.println("testFunc");
	}
}
public class demo_1 {
	public static void main(String[] args) {
		Students stu1 = new Students();
		stu1.age = 20;
		stu1.name = "xiao ming";
		stu1.score = 100.0;
		stu1.seeweight(125.3);//访问private的内容,可以造一个方法来间接访问
		stu1.introduce();
		}
}

对属性和方法的封装,主要是在属性或方法前加上对他们的访问修饰符,并向外提供访问接口。

 构造方法:主要负责对象初始化工作;确保用户操作对象之前,系统保证初始化进行。

构造方法的规则:方法名与类名一致;没有返回类型;方式实现主要为字段赋值。

构造方法的调用:new操作符。


class Student
{
	int age;
	String name;
	double score;
	//Java系统保证每个类都有构造方法
	Student(int newage)//没有返回值什么也不用写,也不用加void
	{
		System.out.println("这是构造方法1");
		age = newage;
	}
	
	Student(int newage,String newname)//没有返回值什么也不用写,也不用加void
	{
		System.out.println("这是构造方法2");
		age = newage;
		name = newname;
	}
	
	Student(int newage,String newname,double newscore)//在Java中,方法是可重载的,这在c语言中不被允许
	{
		System.out.println("这是构造方法3");
		age = newage;
		name = newname;
		score = newscore;
	}
	void putS()
	{
		System.out.println("age ="+age+",name = "+name+",score = "+score);
	}
}

public class demo2 {
	public static void main(String[] args) {
		//构造方法的调用
		Student stu1 = new Student(18,"wang",99.5);//实例化一个对象
		stu1.putS();
		Student stu2 = new Student(18,"yang");
		stu2.putS();
		Student stu3 = new Student(18);
		stu3.putS();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值